Clearing all cookies with JavaScript

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

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

18条回答
  •  花落未央
    2020-11-22 06:31

    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();
            }
        }
    })();
    

提交回复
热议问题