I'm creating cookies which are intended to be shared all across mysite.
This is the code that creates such cookies:
var setCookie = function(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
var path ="path=/;";
document.cookie = cname + "=" + cvalue + ";" + expires + ";" + path;
};
It looks pretty straight forward, and I'm using path=/ to indicate that I want to create or modify always the same cookie all along my site.
The problem is that it is creating one cookie for each URL. With a Mozilla plugin I can see the following:
Cookie Name Value Path
timer_is_enabled true /
timer_is_enabled false /foo
timer_is_enabled true /foo/bar
Which is causing my many bugs because the variables which are being accessed are not one and only, but many independent ones.
Any idea why I'm getting this behavior?
Your code should work as expected, at least regarding the path attribute. Those other cookies may be remnants from earlier tests (sadly, there's normally no way to track the creation date of a given cookie since browsers don't normally keep such information).
I suggest you remove all current cookies from the browser and try again.
That function works ok for me. Ran the following:
setCookie('myCookieKey', 'myCookieValue', 10);
And I got the following:
Related
I'm trying to set my cookies in Javascript the following way
<video id = 'media'></video>
document.addEventListener('DOMContentLoaded', function() {
document.cookie='X-At=$ACCESS_TOKEN$';
document.getElementById('media').src = "$some video link$";
});
However, the cookie just doesn't seem to be added. The file is also hosted on a simpleHttpServer because Chrome seems to ignore pages on local pages. Could someone tell me where the problem is? Note that the cookie gets set when I delete document.getElementById('media').src = "$some video link$";... SoI'm guessing it has to do with setting the source of the element.
Thanks so much.
Found out that cookies are domain specific. So I was unable to set the cookies for the request to a different network, i.e. my file is hosted on a local network 127.0.0.1 and I was trying to send the cookie to a different domain.
The hacky go around for this was to create a proxy server for my request and overwrite the cookie there and redirect the target to my original destination. Couldn't think of a better way to do this.
mate: way of create a cookie like this
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
I am trying to add a popup pause in one day using JS cookies. Here is teh code:
if (document.cookie.indexOf("expirator") >= 0) {
// do not show popup
}
else{
var d = new Date();
var start_date = d.toUTCString();
d.setTime(d.getTime() + (1*24*60*60*1000));
var expireDate = "expires="+d.toUTCString();
document.cookie = "expirator=1;" + expireDate + "; domain=a5w.org; path=/";
// show popup
}
for a strange reason this scipt adds multiple new cookies with the same name ("expirator") instead of updating one. why is that so?
screenshot from FF cookies:
http://a5w.org/up/uploads/mike/2015-10-10/1444519970_cookies.png
You don't update cookies; you need to overwrite them.
Two cookies may have the same name if they were set for different domains or paths.
https://stackoverflow.com/a/1242446/280842
EDIT
There seems to be a bug in Firefox that displays multiple cookies in Firefox cookie manager. See https://bugzilla.mozilla.org/show_bug.cgi?id=504086
My coworker ran into an issue where NO cookie could be set on Chrome via code like this:
document.cookie = "TEST=1; expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
Putting document.cookie into the console immediately after would show results as if I made no change. On refresh of the page, the cookie was not there so it was reporting correctly, just not setting correctly.
The above code would work if he opened a new incognito window and worked for everyone else in general. I removed all his cookies using the dev tools and still had no luck manually setting cookies ( although others would come back that were set via the server headers).
Once he restarted Chrome, it started to behave properly, so it seems like he was running up against some quirk or bug that can no longer be reproduced.
Has anyone else run into this? As of now I am thinking of checking that document.cookie reports back what is expected after setting, and then initiating our cookieless flow for when a user has cookies disabled when things don't match up. I hate the idea of doing that so any suggestions / answers would be great.
The way cookies work, at least in Chrome, is a bit weird.
If you need to change a cookie's value, then you need to add/set each keys one by one.
Try this in your console:
document.cookie; // -> "expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
document.cookie = 'TEST=1';
document.cookie; // -> "TEST=1; expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
Yes, it has added the key, and not replaced the whole cookie with TEST=1.
If you need to remove a key, you can simply provide no value: TEST=.
I hope this will get you out of the cookie nightmare (it was for me).
Make sure to run it on a server (at least a local server) so that document.cookie works.
If you locally run this file in the browser. "document.cookie" wouldn't work.
As another user mentioned, you have to set them one-by-one. These functions can be useful in parsing & applying a cookie string:
function clearCookies(){
var cookies = document.cookie.split(';');
for(i in cookies){
var vals = cookies[i].split('=');
var name = vals.shift(0, 1).trim();
document.cookie = name+'=';
}
}
function parseCookies(cookie){
clearCookies();
var cookies = cookie.split(';');
for(i in cookies){
var vals = cookies[i].split('=');
var name = vals.shift(0, 1).trim();
document.cookie = name+'='+vals.join('=');
}
}
You have to set the domain!
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;domain=" +
window.location.hostname;
}
The expiry date set for the cookie might be the problem. I have come into a problem like this before on Chrome. Set the date to present or future date and test if it would work. Probably that was how Chrome was designed.
We have the same problem in work a while ago, in our case it only happen when we work in local enviroment, after research we crossed an article that said that browser have some kind of problems with localhost:3000, because it recognizes as an insecure page or something like that.
We fixed just by replacing localhost:3000 for 127.0.0.1:3000 (i think that the ip depends on your configuration), and after we replaced that it works perfectly. I hope it helps you.
The following code works fine in FF:
var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = "c_odi" + "=" + $('#orderdetailid').val() + expires + "; path=/";
But not in Chrome. When I'm using Chrome and I do document.cookie in the console to view cookies, the c_odi cookie isn't there. But when I do the same in FF, it is. How can we make cookies work in Chrome? The cookies that were added by PHP are fine, but not this one in JavaScript, and I do need to add this cookie via JavaScript at this point.
This problem can occur if You open Your code as file:///C:/.../xxx.html instead of http:// localhost/xxx.html. Chrome doesn't save cookies (because there is no domain and no http communication) in file:// case.
Few links of interest:
https://gist.github.com/shellscape/02d3a97031e7afdf99d2642f93d59486
Setting Cookies using JavaScript in a local html file
https://bugzilla.mozilla.org/show_bug.cgi?id=536650
https://datatables.net/forums/discussion/46255/save-state-to-cookie-in-file-protocol
Chrome doesn’t store cookies from the pages which are loaded from local file system. For example if you are accessing a HTML file in chrome browser from local file system(ex: file:///C:/Users/deepak.r/Desktop/test.html), cookies are not supported.
Try to replace this line:
document.cookie = "c_odi" + "=" + $('#orderdetailid').val() + expires + "; path=/";
with this one:
document.cookie = "c_odi" + "=" + escape($('#orderdetailid').val()) + expires + "; path=/";
You would have to use unescape when you try to read value, but you'll menage when time comes :)
Seems like it's working for me:
http://jsfiddle.net/rQEnF/3/
At least the cookie shows up in dev tools, as you can see. However, I replaced the jQuery selector $('#orderdetailid').val() with a constant value, as you can see. Is there something wrong with that value or the element containing the value maybe?
Make sure your address bar url matches the domain. In Chrome if you set domain=www.site.com and then test your page in the browser missing out the www. it won't work.
I have found a weird bug in my application and due to my small experience with Javascript I couldn't debug it;
I am trying to set a persistent cookie, which will die after one year from its set (max value in major browsers) but persists and won't be deleted after the browser gets closed. I've been using this code:
// Build the expiration date string:
var expiration_date = new Date();
expiration_date.setYear (expiration_date.getYear () + 1);
expiration_date = expiration_date.toGMTString();
// Build the set-cookie string:
var cookie_string = "test_cookies = true; path=/; expires=" + expiration_date;
// Create/update the cookie:
document.cookie = cookie_string;
I've noticed that the cookie has a session tag when I use cookie manager plugin, and only the ones with this tag get removed when the browser shuts down (others like Wordpress's and such scripts persist).
I changed your syntax over to my style of coding (variables at the top, minimal re-casting, etc.) and the example below works on my localhost quite well.
// Build the expiration date string:
var expiration_date = new Date();
var cookie_string = '';
expiration_date.setFullYear(expiration_date.getFullYear() + 1);
// Build the set-cookie string:
cookie_string = "test_cookies=true; path=/; expires=" + expiration_date.toUTCString();
// Create or update the cookie:
document.cookie = cookie_string;
If you are having problems on a production server, try setting the domain of the cookie as well (www.quirksmode.org/js/cookies.html#link5)
You can also use the max-age attribute.
cookie_string = "test_cookies=true; path=/; max-age=31536000";
One week: max-age=604800
One month: max-age=2628000
One year: max-age=31536000
have you tried using the getFullYear() and setFullYear() methods of the Date instance instead of getYear() and setYear() ? the latter are are deprecated, see here.
hope that helps! cheers.