I'm trying to save a cookie on my site using this function in javascript
setCookie: function(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 + ";path=/";
}
Strangely this doesn't work in Chrome. It works in Firefox though.
If I change the semicolon to comma instead like below, it works in Chrome. But the attributes are set as part of the cookie value instead of attributes that the browser can read.
document.cookie = cname + "=" + cvalue + "," + expires + ",path=/";
Moreover, this only started happening last week. Has anyone else been noticing this? And if so, if there a solution for this?
Thanks.
UPDATE:
There seems to be an issue with the format of the date. I started using max-age instead with an integer value for seconds and it works fine now, even with the semi-colon.
Cookies are usually set by a web-server using the response Set-Cookie HTTP-header. Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP-header.
For Google Chrome the default location for cookies is %LocalAppData%\Google\Chrome\User Data\Default\cookies.
There are only certain fields that are predicated by a semicolon. As per MDN documentation:
Any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:
The attribute values are:
;path=path
;domain=domain
;max-age=max-age
;expires=date
;secure
The below code block works in Chrome Version 58.0.3029.96 (64-bit) for me.
var cname = "MyCookie";
var cvalue = "kjqwrQR1515jetrQT26jo2u5";
var expires = " ;expires=" + Date.now() + 100000;
document.cookie = cname + "=" + cvalue + expires + " ;path=/";
If this format doesn't work for you, what values are your cname
cvalue
, and exdays
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With