views:

5776

answers:

4

How do you delete all the cookies for the current domain using javascript?

+2  A: 

As far as I know there's no way to do a blanket delete of any cookie set on the domain. You can clear a cookie if you know the name and if the script is on the same domain as the cookie.

You can set the value to empty and the expiration date to somewhere in the past:

var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString();

There's an excellent article here on manipulating cookies using javascript.

ConroyP
+4  A: 

You can get a list by looking into the document.cookie variable. Clearing them all is just a matter of looping over all of them and clearing them one by one.

Sec
+8  A: 
function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
     var cookie = cookies[i];
     var eqPos = cookie.indexOf("=");
     var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
     document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}
Robert J. Walker
Nice one, but after experimenting, I found that a site can have only one cookie without =, and then it is a nameless cookie, you get its value actually.So if eqPos == 1, you should do `name = ""` instead, to erase the nameless value.
PhiLho
Thanks! Works, at least for multiple cookies from one domain (which is what I needed :)
axk
A: 

hello i found some javascript which clear coookies. all its fine but it leaves one position in this cookies - PHPSESSID. Any help how can i delete it, using this script or any other? i have to add that i've never programmed in java. I would like use it in c# webbrowser control, just like webbrowser.Navigate("javascript: and code of script here"); thank you for your reply

void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())