venkatachalam venkatachalam - 6 months ago 23
Javascript Question

How can I delete all cookies with JavaScript?

I have written code to save cookies in JavaScript. Now I need to clear the cookies irrespective of values that I assigned.

Are there any script modules to delete all cookies that were generated by Javascript?

My Sample Code:



document.cookie = 'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}


How else could I clear all of the cookies?

Will there will be any problems when I test the code on the webserver?

Answer

But on the face of it it looks OK - if you call your eraseCookie() on each of the cookies that you read from document.cookie, then all the cookies would be gone.

Maybe something like this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All this with caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.