I have this real strange problem with client side javascript setting cookies. I'm developing a little 1 page demo at the moment to use cookies to store some 'preferences'. Please note that I can't use a server side language for this demo or any 3rd party jQuery plugins.
So I've written a javascript object to set a cookie:
var cookie = {
set: function (name,value,exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=name + "=" + value;
console.log(document.cookie);
}
}
cookie.set('foo','bar',2);
console.log(document.cookie);
It just returns an empty string. I've gone into Chrome console to see if I can do it via directly modifying document.cookie
> document.cookie = "foo=bar";
"foo=bar"
> document.cookie
""
How do you set a cookie via client side javascript?
Edit: I am not in incognito mode and cookies are enabled.
HttpOnly cookies cannot be accessed from Javascript and session cookies are usually set as HttpOnly cookies. See also this StackOverflow question:
How to read a secure cookie using JavaScript
So... check whether the cookie you want to read has the 'HttpOnly' flag set... If so, you know the culprit.
It's not a bug, it's a feature!
You can't set cookies by the look of things if its not running in a web server.
file:///C:/Users/me/Desktop/demo/demo.html
however:
http://localhost/demo/demo.html works.
This worked for me when ran from localhost, running chrome 28.0.1472.0 canary:
<!DOCTYPE html>
<html>
<head>
<title>localhost cookie</title>
</head>
<body>
<script type="text/javascript">
console.log(document.cookie);
var myCookie = "mycookie=hellocookie";
document.cookie = myCookie;
</script>
</body>
</html>
Run it in a server, visit the page and look at your cookie store, refresh the page and look at your console.
It did not set a cookie when opened as a file but worked every time when opened from the server.
For usage and docs, see here:
https://developer.mozilla.org/en-US/docs/DOM/document.cookie
If you are in Incognito Mode or have cookies disabled, it won't work.
You might have set a wrong path for the cookie.
In my case I'd set the path in the cookie to /foo because the application is normally on address http://example.org/foo.
However, during tests I'd opened the application on the default address http://localhost:3000 which allowed me to create cookies with the path /foo but not read them.
The solution was to test the application on address http://localhost:3000/foo.
cookie will not work if you directly open your file, let's say index.html
file:///C:/Users/me/Desktop/index.html
however:
cookie will work if page (index.html) is opened using a light weight server or
local server
http://localhost/demo/demo.html works.
or
http://127.0.0.1:5500/temp6.html
For live sever in VS Code you can use Live Serve by Ritwick Dey
Related
I am making a .html file that is meant to be open locally, therefore not accessed via http:// but via file:///
Firefox rejects the cookie I try to create in javascript, saying there is already a cookie HTTP-Only:
document.cookie = cname + "=" + cvalue + ";expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;HttpOnly;SameSite=Strict;";
Is there a way to use cookies for a local page ?
Cookies are not set for local pages via file:///. See here for more information: Setting Cookies using JavaScript in a local html file
Browsers do not store cookies for the file:// url protocol, although it may depend on the browser anyway
e.g launching chrome with --enable-file-cookies
Let's say I am logged in (with login/password) on a website/service https://example.com in a browser. If I open Developer tools, I can run document.cookie in the console and copy the string containing all the cookies associated with the current website.
Then I open a new incognito window, I go to https://example.com. Of course, I'm not logged in. I can remove the current cookies with the method described in Clearing all cookies with JavaScript in the Developer tools console, and then restore the cookies copied before:
document.cookie = "<the string that I copied before>"
Then after a page reload (F5), I expected to be logged-in again, but it did not work. The cookies set with document.cookie = "<the string that I copied before>" are not kept. (For example, in the case of Reddit, it did not work.)
What's wrong with this JS approach to set cookies in the "Developer tools" from a previous session from another browser? Shouldn't it work?
Normally, the session id is set to server only, you can not get session id in JS/console.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Restrict_access_to_cookies
I need to delete gmail cookies set in my chrome browser, using chrome extension , but it can delete all cookies other then Gmail cookies, then I noticed that Gmail cookies are httponly, Is there a way to remove them using javascript chrome extension..
Thanks :)
Chrome extensions can use chrome.cookies API, that has access to all cookies in the cookie store, including httpOnly.
The documentation for the API is here.
Note that this API requires declaring a permission and will not work from content scripts.
This one works absolutely fine for deleting every cookie, even if it is httponly
chrome.cookies.getAll({'domain':'accounts.google.com'},function(cookie){
for(i=0;i<cookie.length;i++){
var prefix = "https://";
var url = prefix + cookie[i].domain + cookie[i].path;
chrome.cookies.remove({'url':url , 'name':cookie[i].name},function(cookie){ });
}
});
The point of HTTPOnly cookies is not let javascript to access them.
So basically you can not read them.
If you want to delete them you can do it from the options that offers browser
Here's the JavaScript code:
var tmp = escape(document.cookie.match(/TestSession=[^;]+(;|$)/)[0]);`
With MVC, if I have this it works:
var cookie = new HttpCookie("TestSession", "SomeValue") {
Expires = DateTime.Now.AddYears(1)
};
But if I add:
cookie.Domain = "Test.com";
or
{ Expires = DateTime.Now.AddYears(1), Domain = "Test.com" };
The JavaScript has tmp as null or undefined.
Any ideas?
Remember, you cannot access cookies of another domain. So, if you're running the site under a different domain than test.com you won't be able to access the cookie.
Note: this will also be true when working from http://localhost - as localhost and test.com are not of the same origin.
To remedy the issue you could check the current host on the server and set the domain accordingly.
Update (after comment)
As noted by Andrei, you could also add a host entry to your local host file that maps test.com to localhost. Though, you'll need to remember to comment it out when you need to navigate to the production version of the site.
I am using a jQuery plugin to set cookies and when I use localhost for the domain it will not store the cookie.
Here is the plugin I am using with jQuery 1.2.6.
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
Below is the code that I am using. You can see it does not like localhost, and I am running it from a development web server on localhost. One detail is that I am running off port 4005 but that should not affect the domain, AFAIK.
$(function() {
console.log('Testing');
var one = $.cookie('Test.One');
var two = $.cookie('Test.Two');
var three = $.cookie('Test.Three');
console.log(['one', one]);
console.log(['two', two]);
console.log(['three', three]);
$('#div1').text(one);
$('#div2').text(two);
$('#div3').text(three);
$.cookie('Test.One', 'Test 1');
$.cookie('Test.Two', 'Test 2', { path: '/' });
$.cookie('Test.Three', 'Test 3', { path: '/', domain: 'localhost' });
});
I had similar problem with setting cookies. Make up a domain name and add it to your hosts file as 127.0.0.1. Then run web application on that domain.
I think the domain name of a cookie must have exactly two dots (not counting the final dot after the TLD). So .something.localhost is okay, .google.com is okay, but .localhost or google.com is not. But a glance at RFC 2965 suggests that it's more complicated than that... you might want to read that document, especially section 3.3 (and/or its precursor, RFC 2109).
I updated the jQuery plugin to not add the domain to the cookie when it is localhost. That solves my problem without touching the hosts file.
var domain = (options.domain && options.domain !== 'localhost') ? '; domain=' + (options.domain) : '';
I'm using Code Ignitor, and setting the domain to an empty string fixed my problem while working on the application on localhost. I believe this is the better solution as everyone in the development team then doesn't need to mess with their hosts files on Windows.
Production domain values can be put in the config.php of Code Ignitor when deployed on a live site.
I tried setting the host file to use an alternate name (local.acme.com) and I can now set cookies on that domain. It seems I cannot set cookies on localhost, at least not with Firefox. I do not recall that being a restriction for cookies. I would like to understand what is going on here.
Also, I did try just making the domain in the hosts file simply "dev" but that did not work. I had to use a name that ended in .com or another tld to make it work.
Simplest solution for me to resolve this was to use 127.0.0.1 instead of localhost ;-)
That works fine in Firefox!
Cookie needs to specify SameSite attribute, None value used to be the default, but recent browser versions made Lax the default value to have reasonably robust defense against some classes of cross-site request forgery (CSRF) attacks.
Along with Domain=localhost your cookie should look something like this
document.cookie = `${name}=${value}${expires}; Path=/; Domain=localhost; SameSite=Lax`;
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite