Clearing all cookies with JavaScript

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

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

18条回答
  •  青春惊慌失措
    2020-11-22 06:33

    I don't know why the first voted answer doesn't work for me.

    As this answer said:

    There is no 100% solution to delete browser cookies.

    The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

    Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

    So my idea is to add a Cookie version control with the full set of setting, getting, removing of cookies:

    var cookie_version_control = '---2018/5/11';
    
    function setCookie(name,value,days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name+cookie_version_control + "=" + (value || "")  + expires + "; path=/";
    }
    
    function getCookie(name) {
        var nameEQ = name+cookie_version_control + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    
    function removeCookie(name) {   
        document.cookie = name+cookie_version_control+'=; Max-Age=-99999999;';  
    }
    

提交回复
热议问题