如何使用JavaScript删除当前域的所有cookie ?


当前回答

如果你只关心清除安全源上的Cookie,你可以使用Cookie Store API和它的.delete()方法。

cookieStore.getAll().then(cookies => cookies.forEach(cookie => {
    console.log('Cookie deleted:', cookie);
    cookieStore.delete(cookie.name);
}));

访问caniuse.com表,查看Cookie Store API的浏览器支持情况。

其他回答

这是一个简单的代码删除所有的JavaScript cookie。

function deleteAllCookies(){
   var cookies = document.cookie.split(";");
   for (var i = 0; i < cookies.length; i++)
     deleteCookie(cookies[i].split("=")[0]);
}

function setCookie(name, value, expirydays) {
 var d = new Date();
 d.setTime(d.getTime() + (expirydays*24*60*60*1000));
 var expires = "expires="+ d.toUTCString();
 document.cookie = name + "=" + value + "; " + expires;
}

function deleteCookie(name){
  setCookie(name,"",-1);
}

执行deleteAllCookies()函数清除所有cookie。

document.cookie.split(";").forEach(function(c) { 
    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
});
//clearing local storage
localStorage.clear();

我有一些更复杂和面向oop的cookie控制模块。它还包含deleteAll方法来清除所有现有的cookie。请注意,这个版本的deleteAll方法有设置path=/,这会导致删除当前域中的所有cookie。如果你只需要从某些范围删除cookie,你将不得不升级这个方法,我添加动态路径参数到这个方法。

主要有Cookie类:

import {Setter} from './Setter';

export class Cookie {
    /**
     * @param {string} key
     * @return {string|undefined}
     */
    static get(key) {
        key = key.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');

        const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');
        const matches = document.cookie.match(regExp);

        return matches
            ? decodeURIComponent(matches[1])
            : undefined;
    }

    /**
     * @param {string} name
     */
    static delete(name) {
        this.set(name, '', { expires: -1 });
    }

    static deleteAll() {
        const cookies = document.cookie.split('; ');

        for (let cookie of cookies) {
            const index = cookie.indexOf('=');

            const name = ~index
                ? cookie.substr(0, index)
                : cookie;

            document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
        }
    }

    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        Setter.set(name, value, opts);
    }
}

Cookie setter方法(Cookie.set)相当复杂,所以我把它分解到其他类中。这里有一个代码:

export class Setter {
    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        value = Setter.prepareValue(value);
        opts = Setter.prepareOpts(opts);

        let updatedCookie = name + '=' + value;

        for (let i in opts) {
            if (!opts.hasOwnProperty(i)) continue;

            updatedCookie += '; ' + i;

            const value = opts[i];

            if (value !== true)
                updatedCookie += '=' + value;
        }

        document.cookie = updatedCookie;
    }

    /**
     * @param {string} value
     * @return {string}
     * @private
     */
    static prepareValue(value) {
        return encodeURIComponent(value);
    }

    /**
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     * @private
     */
    static prepareOpts(opts = {}) {
        opts = Object.assign({}, opts);

        let {expires} = opts;

        if (typeof expires == 'number' && expires) {
            const date = new Date();

            date.setTime(date.getTime() + expires * 1000);

            expires = opts.expires = date;
        }

        if (expires && expires.toUTCString)
            opts.expires = expires.toUTCString();

        return opts;
    }
}

一个衬套

以防你想快速粘贴进去…

document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });

和bookmarklet的代码:

javascript:(function(){document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); })();

我在这里贡献是因为这个功能将允许您删除所有cookie(匹配路径,默认为no-path或\),也包括设置为包含在子域上的cookie

function clearCookies( wildcardDomain=false, primaryDomain=true, path=null ){
  pathSegment = path ? '; path=' + path : ''
  expSegment = "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"
  document.cookie.split(';').forEach(
    function(c) { 
      primaryDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment))
      wildcardDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment + '; domain=' + document.domain))
    }
  )
}