venkatachalam venkatachalam - 1 year ago 96
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();
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) {

How else could I clear all of the cookies?

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

Answer Source

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++)

All this with caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download