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.
cookie= operation does not overwrite all cookies. It only sets the mentioned cookie user . There are few limitations: The name=value pair, after encodeURIComponent , should not exceed 4KB.
The document. cookie attribute simply returns a string containing a semicolon and a space separated list of all cookies (i.e. name=value pairs, for example, firstName=Fabulous; lastName=Designs; ). This string does not include any of the cookie's characteristics, such as expires, path, domain, and so on.
You are most likely dealing with httponly cookies. httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With