How do you delete all the cookies for the current domain using JavaScript?
//Delete all cookies
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:01 GMT;' +
'path=' + '/;' +
'domain=' + window.location.host + ';' +
'secure=;';
}
}
Simpler. Faster.
function deleteAllCookies() {
var c = document.cookie.split("; ");
for (i in c)
document.cookie =/^[^=]+/.exec(c[i])[0]+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
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.
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";
}
}
Note that this code has two limitations:
HttpOnly
flag set, as the HttpOnly
flag disables Javascript's access to the cookie.Path
value. (This is despite the fact that those cookies will appear in document.cookie
, but you can't delete it without specifying the same Path
value with which it was set.)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.
An answer influenced by both second answer here and W3Schools
document.cookie.split(';').forEach(function(c) {
document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';
});
Seems to be working
edit: wow almost exactly the same as Zach's interesting how Stack Overflow put them next to each other.
edit: nvm that was temporary apparently