Knowpapa.com - a developer's blog

Removing a Cookie with JavaScript | JS Tutorial

When you write a cookie with JavaScript, you are actually jumping the traditional bounds of the browser object by storing information on the hard disk.

While writing a cookie on to the hard disk is allowed, you cannot delete a cookie directly by using JavaScript.

In fact this restriction has been deliberately built into JavaScript to prevent cookies from wreaking havoc on the users’ hard disk.

You can however make the cookie ineffective by changing its expiration date to some time in the past. When you do that the web browser eventually deletes it as an expired cookie.

The following code in JavaScript shows how you can modify the expiry time of an existing cookie:

function deleteCookie () {
var expiryDate = new Date();
// Fetch the current date
// Change the variable to  a time in the past. . .
expiryDate = expiryDate.setTime (expiryDate.getTime() - 999999999999);
// retrieve the cookie
var cookieValue = getCookie (‘myCookie’);
// Finally, set the cookie’s new expiry date to the past time

document.cookie = ‘myCookie’ + “=” + cookieValue + “;
expires=” + expiryDate.toGMTString();
//see note on GMT  conversion below
}

**Note that cookie expiration dates are normally stored in the standard Greenwich Mean
Time format. (You can change a date to the GMT format by using the toGMTString() method of the core JavaScript Date object.)

***Because the whole purpose of using cookies is for a server-side applications to keep track of client states – creating, modifying or removing a cookie are better handled with a server side language like PHP / ASP or any other CGI script.