Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does document.cookie work?

If I get Chrome to show me document.cookie by going into the console and typing document.cookie; it'll give me, say:

"name=John; gender=male";

But then if I type in, say, document.cookie = 5; all it does is add 5; to the start of the string, so I get:

"5; name=John; gender=male";

If I try document.cookie = null; then it doesn't even do anything.

How can this be? It's a variable, isn't it? So why isn't the assignment operator working the way it should? Is it actually just a bit of syntactic sugar rather than a real variable? And if so, what precisely is the sugar covering up?

like image 779
Jack M Avatar asked Jul 22 '11 15:07

Jack M


People also ask

Is Document cookie a string?

The document. cookie property looks like a normal text string. But it is not. Even if you write a whole cookie string to document.

How do I alert a Document in cookies?

One useful Javascript convenience function I ran across a while back is the javascript:alert(document. cookie) browser scriptlet. If you type this into the address bar of your browser, it will pop up a list of all of the cookies currently set in this domain (try it!)

Are cookies automatically sent to server?

Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web Storage API ( localStorage and sessionStorage ) and IndexedDB.


2 Answers

document.cookie has very special behavior. As you've seen, assigning to it adds (or updates) a cookie (or multiple cookies), rather than replacing all of the cookies. It's very unusual.

Read all about it on MDN.

like image 172
T.J. Crowder Avatar answered Sep 30 '22 03:09

T.J. Crowder


Why not have a look at MDN?

The string on the right side of the assignment operator to document.cookies should be a semicolon separated list of key-value pairs, i.e. document.cookie = "aKey=5" will set/update the aKey cookie.

So yes, document.cookie shows special behavior.

like image 28
Alexander Gessler Avatar answered Sep 30 '22 03:09

Alexander Gessler