9

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.

zjmiller
  • 2,709
  • 4
  • 29
  • 30

3 Answers3

10

Setting document.cookie is specified by the DOM 2 HTML specification. Setting it to an empty string should result in an error according to that specification.

It's a badly designed interface. The relationship is a fucked up one. You don't have to visualise it, you just have to put up with it.

Jim
  • 72,985
  • 14
  • 101
  • 108
  • +1 for your last paragraph. That pretty much sums up the situation. – Reid Jul 02 '11 at 21:57
  • `You don't have to visualise it` Then how are we ever supposed to _understand_ it? The OP (and I) are trying to `conceptualize the relationship between the cookies stored by the browser and the document.cookie made available via the DOM.` We can't use an interface that we don't understand. – Nateowami Jul 09 '14 at 08:59
8

document.cookie doesn't really behave normally. Browsers treat calls to reading and writing document.cookie different from 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.

Shiva
  • 20,575
  • 14
  • 82
  • 112
Matchu
  • 83,922
  • 18
  • 153
  • 160
2

As already mentioned, document.cookie is not a normal string. When you read it, you get all cookies. When you set it, you set one new cookie. Thus, you cannot clear all cookies this way.

If you want to clear all cookies, there are a number of other SO questions on the same topic. This one seems pretty clear: Clearing all cookies with JavaScript. You can find a zillion other recommendations with a Google search for how do you remove all cookies for a site with javascript.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979