Clearing all cookies with JavaScript
How do you delete all the cookies for the current domain using JavaScript?
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:
- It will not delete cookies with
HttpOnly
flag set, as theHttpOnly
flag disables Javascript's access to the cookie. - It will not delete cookies that have been set with a
Path
value. (This is despite the fact that those cookies will appear indocument.cookie
, but you can't delete it without specifying the samePath
value with which it was set.)
One liner
In case you want to paste it in quickly...
document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
And the code for a bookmarklet :
javascript:(function(){document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); })();