Clearing all cookies with JavaScript

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

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

18条回答
  •  终归单人心
    2020-11-22 06:34

    After a bit of frustration with this myself I knocked together this function which will attempt to delete a named cookie from all paths. Just call this for each of your cookies and you should be closer to deleting every cookie then you were before.

    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 always different browsers have different behaviour but this worked for me. Enjoy.

提交回复
热议问题