Clearing all cookies with JavaScript

2018-12-31 12:47发布

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

17条回答
春风洒进眼中
2楼-- · 2018-12-31 13:15

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;
        }
    }
})();
查看更多
不流泪的眼
3楼-- · 2018-12-31 13:16
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 the HttpOnly 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 in document.cookie, but you can't delete it without specifying the same Path value with which it was set.)
查看更多
孤独寂梦人
4楼-- · 2018-12-31 13:18
//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=;';
    }
}
查看更多
皆成旧梦
5楼-- · 2018-12-31 13:19

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.

查看更多
若你有天会懂
6楼-- · 2018-12-31 13:19

Jquery:

var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}

vanilla JS

function clearListCookies()
{   
 var cookies = document.cookie.split(";");
 for (var i = 0; i < cookies.length; i++)
  {   
    var spcook =  cookies[i].split("=");
    deleteCookie(spcook[0]);
  }
  function deleteCookie(cookiename)
   {
    var d = new Date();
    d.setDate(d.getDate() - 1);
    var expires = ";expires="+d;
    var name=cookiename;
    //alert(name);
    var value="";
    document.cookie = name + "=" + value + expires + "; path=/acc/html";                    
}
window.location = ""; // TO REFRESH THE PAGE
}
查看更多
倾城一夜雪
7楼-- · 2018-12-31 13:20

And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.com, mydomain.com etc):

(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();
        }
    }
})();
查看更多
登录 后发表回答