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


当前回答

如果你想使用js-cookie npm包并按名称删除cookie:

import cookie from 'js-cookie'

export const removeAllCookiesByName = (cookieName: string) => {
  const hostParts = location.host.split('.')
  const domains = hostParts.reduce(
    (acc: string[], current, index) => [
      ...acc,
      hostParts.slice(index).join('.'),
    ],
    []
  )
  domains.forEach((domain) => cookie.remove(cookieName, { domain }))
}

其他回答

一个衬套

以防你想快速粘贴进去…

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

这个答案受到第二个答案和W3Schools的影响

document.cookie.split(';').forEach(function(c) {
  document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';
});

似乎有效果

编辑:哇,几乎和扎克的Stack Overflow把它们放在一起的有趣方式一模一样。

编辑:NVM显然是暂时的

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

我们可以这样做:

deleteAllCookies=()=>
      {
      let c=document.cookie.split(';')
      for(const k of c)
         {
         let s=k.split('=')
         document.cookie=s[0].trim()+'=;expires=Fri, 20 Aug 2021 00:00:00 UTC'
         }
      }

用法:

deleteAllCookies()

截止日期是这个答案之前的任意一天;它可以是当天之前的任何日期 在JS中,你不能基于路径读取cookie 在JS中,你只能设置或获取cookie

在经历了一些挫折之后,我自己拼凑了这个函数,它将尝试从所有路径中删除一个命名的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 + ';';
    }
}

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