permalink

Cookies - How to Eat one in Javascript ; )

If you have ever dealt with something that appears a 5 minute deal in programming, only to become several hours of torture, you know the price we pay for horrible documentation or incomplete references.

I encountered this experience a short time ago while trying to delete a cookie, theoretically a one liner in Javascript!

Creating the Cookie

document.cookie => That gets you access to the cookie creation mechanism in Javascript.

So let’s create a couple cookies:

document.cookie = ‘BlackOreo=chocolate; path=/’;
document.cookie = ‘WhiteOreo=whitechocolate; path=/fridge/overhere/; ’ ;

Eating the Cookie or Deleting it

Theoretically setting the cookie to expire is enough, you will see many examples on the web of that, but most will not work! Why? The code is simply either wrong or incomplete.

The Black Oreo Case - Not as Simple as you Thought!

To delete a cookie that previously existed, you must set it to a temporary value, and then immediately make it expire. If you do not set it that way, the cookie will not be deleted! Also do not send the domain reference, or it will fail!

So to eat or delete the BlackOreo cookie from above you must do something like this:

document.cookie = ’BlackOreo=gone; expires=Thu, 2 Aug 1970 20:47:11 UTC; path=/’;

The White Oreo Case - Complicated Enough for You?

What if the cookie belongs to a subdirectory, or sub-domain, what should you do? Here you still set the cookie value to something, and make it expire, but on this one you will also set the domain and the path.

var domainTo = document.domain;
document.cookie = ‘WhiteOreo=gone; domain=’ + domainTo + ‘; expires=Thu, 2 Aug 1970 20:47:11 UTC;  path=/fridge/overhere/’;

So there you go, believe me these are helpful, they will save you a lot of time, and now the web has some better documentation too.

Yes those examples actually work, you just need to setup the Javascript… in case you were wondering I do like Oreos!

P.S. Don’t know Javascript, no problem.

Share |
blog comments powered by Disqus

Notes