1. Technology

JavaScript By Example

Cookies: 7. Deleting A Cookie

By

A session cookie is deleted automatically when the browser is closed. First party cookies are also deleted automatically when the expiry date/time that was set when the cookie was created is reached. There should seldom therefore be a neded to actually delete a cookie since it will delete itself at the time it has been told to.

In fact there is no specific command for deleting a cookie and so for those situations where you actually do need to delete a cookie it isn't immediately obvious how to do it.

In fact if you know how to replace cookies and understand how the expiry date determines when a cookie will be deleted it becomes fairly obvious how we can delete a cookie despite there being no separate command to do so. If we replace the existing cookie with a new first party cookie having an expiry date in the past then the old cookie is replaced by the new one and is then immediately deleted since the expiry dat/time has passed.

This example demonstrates how we can use the same function to delete cookies that we set up in the earlier examples to write cookies. To make it obvious that the intention is to delete the cookie we set up a variable called deleteCookie and give it a value of -1. We can then substitute this for the number of days that the cookie is to be kept for. That then sets the expiry date of the new cookie to yesterday and so the cookie is considered to have already been deleted.


var deleteCookie = -1;
writeCookie = function(cname, cvalue, days,opt) {
var dt, expires, option;
if (days) {
dt = new Date();
dt.setTime(dt.getTime()+(days*24*60*60*1000));
expires = "; expires="+dt.toGMTString();
} else expires = '';
if (opt) {
if ('/' = substr(opt,0,1)) option = "; path="+opt;
else option = "; domain="+opt;
} else option = '';
document.cookie = cname+"="+cvalue+expires+option;
}
 
writeCookie('oneweekcookie','',deleteCookie);

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example
  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Cookies
  7. JavaScript By Example - Cookies: Deleting A Cookie

©2014 About.com. All rights reserved.