Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would setting document.cookie not work in Chrome?

Tags:

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.

like image 866
Dave Stein Avatar asked Oct 13 '14 21:10

Dave Stein


People also ask

How do I enable cookies for HTML?

Click "Site Settings". Click "Cookies and site data". In the Privacy and security section, click Content Settings. Click the slider to "Allow sites to save and read cookie data (recommended)."

Are cookies automatically set?

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.


1 Answers

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 replace the whole cookie with TEST=1.

If you need to remove a key, you can simple provide no value: TEST=.

I hope this will get you out of the cookie nightmare (it was for me).

like image 138
avetisk Avatar answered Sep 18 '22 17:09

avetisk