Clearing all cookies with JavaScript

后端 未结 18 1008
别那么骄傲
别那么骄傲 2020-11-22 05:55

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

相关标签:
18条回答
  • 2020-11-22 06:11

    I found a problem in IE and Edge. Webkit browsers (Chrome, safari) seem to be more forgiving. When setting cookies, always set the "path" to something, because the default will be the page that set the cookie. So if you try to expire it on a different page without specifying the "path", the path won't match and it won't expire. The document.cookie value doesn't show the path or expiration for a cookie, so you can't derive where the cookie was set by looking at the value.

    If you need to expire cookies from different pages, save the path of the setting page in the cookie value so you can pull it out later or always append "; path=/;" to the cookie value. Then it will expire from any page.

    0 讨论(0)
  • 2020-11-22 06:16

    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;
            }
        }
    })();
    
    0 讨论(0)
  • 2020-11-22 06:17

    Figured I'd share this method for clearing cookies. Perhaps it may be helpful for someone else at some point.

    var cookie = document.cookie.split(';');
    
    for (var i = 0; i < cookie.length; i++) {
    
        var chip = cookie[i],
            entry = chip.split("="),
            name = entry[0];
    
        document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }
    
    0 讨论(0)
  • 2020-11-22 06:17

    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
    }
    
    0 讨论(0)
  • 2020-11-22 06:18

    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=/"); }); })();
    
    0 讨论(0)
  • 2020-11-22 06:18

    Functional Approach + ES6

    const cookieCleaner = () => {
      return document.cookie.split(";").reduce(function (acc, cookie) {
        const eqPos = cookie.indexOf("=");
        const cleanCookie = `${cookie.substr(0, eqPos)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;`;
        return `${acc}${cleanCookie}`;
      }, "");
    }
    

    Note: Doesn't handle paths

    0 讨论(0)
提交回复
热议问题