zjmiller zjmiller - 5 months ago 11
Javascript Question

If document.cookie is a string, why doesn't document.cookie = "" delete all of the relevant site's cookies?

I think knowing the answer to this would help me conceptualize the relationship between the cookies stored by the browser and the document.cookie made available via the DOM.

Answer

document.cookie doesn't really behave normally. Browsers treat calls to reading and writing document.cookie differently than most calls to object properties.

Setting document.cookie doesn't set the entire cookie string. Instead, it adds cookies. For example:

alert(document.cookie); // The existing cookie string is "foo=bar; spam=eggs"
document.cookie = "hello=world; lol=cats";
alert(document.cookie); // The cookie string might now say "foo=bar; spam=eggs; hello=world; lol=cats"

Though the order of the cookies may vary, the snippet still illustrates the point. Setting document.cookie sets the cookies specified, but doesn't remove a cookie just because it's not mentioned in the new string. It'd be too easy to make mistakes.

Of course, I'm not totally sure why the API was built this way. I suspect things might be different if we were writing the cookie API today, and would actually have read, write, delete, etc., functions. However, this is what we've got.