How do you delete all the cookies for the current domain using JavaScript?
After testing almost ever method listed in multiple style of browsers on multiple styles of cookies, I found almost nothing here works even 50%.
Please help correct as needed, but I'm going to throw my 2 cents in here. The following method breaks everything down and basically builds the cookie value string based on both the settings pieces as well as including a step by step build of the path string, starting with /
of course.
Hope this helps others and I hope any criticism may come in the form of perfecting this method. At first I wanted a simple 1-liner as some others sought, but JS cookies are one of those things not so easily dealt with.
;(function() {
if (!window['deleteAllCookies'] && document['cookie']) {
window.deleteAllCookies = function(showLog) {
var arrCookies = document.cookie.split(';'),
arrPaths = location.pathname.replace(/^\//, '').split('/'), // remove leading '/' and split any existing paths
arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ]; // array of cookie settings in order tested and found most useful in establishing a "delete"
for (var i in arrCookies) {
var strCookie = arrCookies[i];
if (typeof strCookie == 'string' && strCookie.indexOf('=') >= 0) {
var strName = strCookie.split('=')[0]; // the cookie name
for (var j=1;j<=arrTemplate.length;j++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';'; // made using the temp array of settings, putting it together piece by piece as loop rolls on
if (j == 1) document.cookie = strValue;
else {
for (var k=0;k<=arrPaths.length;k++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strPath = arrPaths.slice(0, k).join('/') + '/'; // builds path line
strValue = strValue.replace('{path}', strPath);
document.cookie = strValue;
}
}
}
}
}
}
}
showLog && window['console'] && console.info && console.info("\n\tCookies Have Been Deleted!\n\tdocument.cookie = \"" + document.cookie + "\"\n");
return document.cookie;
}
}
})();