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


当前回答

简单。得更快。

function deleteAllCookies() {
 var c = document.cookie.split("; ");
 for (i in c) 
  document.cookie =/^[^=]+/.exec(c[i])[0]+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";    
}

其他回答

我想分享一下清除cookie的方法。也许这在某些时候对其他人是有帮助的。

var cookie = document.cookie.split(';');

for (var i = 0; i < cookie.length; i++) {

    var chip = cookie[i],
        entry = chip.split("="),
        name = entry[0];

    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
document.cookie.split(";").forEach(function(c) { 
    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
});
//clearing local storage
localStorage.clear();

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

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

这对我来说很管用:

function deleteCookie(name) {
  document.cookie = 
    `${name}=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/`;

    // Remove it from local storage too
    window.localStorage.removeItem(name);
}

function deleteAllCookies() {
  const cookies = document.cookie.split("; ");

  cookies.forEach((cookie) => {
    const name = cookie.split("=").shift();
    this.deleteCookie(name);
  });

  // Some sites backup cookies in `localStorage`
  window.localStorage.clear();
}

这是一个简单的代码删除所有的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。