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


当前回答

函数方法+ 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}`;
  }, "");
}

注意:不处理路径

其他回答

一个衬套

以防你想快速粘贴进去…

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。只需为每个cookie调用这个函数,就可以更接近于删除每个cookie。

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 + ';';
    }
}

不同的浏览器有不同的行为,但这对我来说是有效的。 享受。

如果你有jquery的访问。Cookie插件,你可以用这种方式删除所有的Cookie:

for (var it in $.cookie()) $.removeCookie(it);

如果你只关心清除安全源上的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的浏览器支持情况。

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