Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome not saving cookies with semicolon

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.

like image 467
fractal5 Avatar asked May 05 '17 14:05

fractal5


People also ask

Are cookies set automatically?

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.

Where are chrome cookies stored?

For Google Chrome the default location for cookies is %LocalAppData%\Google\Chrome\User Data\Default\cookies.


1 Answers

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?

like image 155
Kyle Richardson Avatar answered Oct 11 '22 03:10

Kyle Richardson