Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - Why would setting document.cookie not work in Chrome?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...