Problem
Using JavaScript, how do you erase all cookies for the current domain?
Asked by polarbear
Solution #1
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";
}
}
There are two limits to this code:
Answered by Robert J. Walker
Solution #2
If you want to swiftly paste it in…
document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
And here’s the bookmarklet code:
javascript:(function(){document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); })();
Answered by Craig Smedley
Solution #3
And here’s another to erase all cookies across all pathways and domain variants (www.mydomain.com, mydomain.com, and so on):
(function () {
var cookies = document.cookie.split("; ");
for (var c = 0; c < cookies.length; c++) {
var d = window.location.hostname.split(".");
while (d.length > 0) {
var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
var p = location.pathname.split('/');
document.cookie = cookieBase + '/';
while (p.length > 0) {
document.cookie = cookieBase + p.join('/');
p.pop();
};
d.shift();
}
}
})();
Answered by Jan
Solution #4
After some irritation with this, I whipped up this code that will attempt to erase a named cookie from all pathways. Simply repeat this procedure for each of your cookies, and you should be closer to erasing all of them than you were previously.
function eraseCookieFromAllPaths(name) {
// This function will attempt to remove a cookie from all paths.
var pathBits = location.pathname.split('/');
var pathCurrent = ' path=';
// do a simple pathless delete first.
document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';
for (var i = 0; i < pathBits.length; i++) {
pathCurrent += ((pathCurrent.substr(-1) != '/') ? '/' : '') + pathBits[i];
document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;' + pathCurrent + ';';
}
}
As with all browsers, different browsers behave differently, however this worked for me. Enjoy.
Answered by AnthonyVO
Solution #5
You can delete all cookies if you have access to the jquery.cookie plugin:
for (var it in $.cookie()) $.removeCookie(it);
Answered by jichi
Post is based on https://stackoverflow.com/questions/179355/clearing-all-cookies-with-javascript