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


当前回答

Jquery:

var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}

香草JS

function clearListCookies()
{   
 var cookies = document.cookie.split(";");
 for (var i = 0; i < cookies.length; i++)
  {   
    var spcook =  cookies[i].split("=");
    deleteCookie(spcook[0]);
  }
  function deleteCookie(cookiename)
   {
    var d = new Date();
    d.setDate(d.getDate() - 1);
    var expires = ";expires="+d;
    var name=cookiename;
    //alert(name);
    var value="";
    document.cookie = name + "=" + value + expires + "; path=/acc/html";                    
}
window.location = ""; // TO REFRESH THE PAGE
}

其他回答

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

    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i];
        const eqPos = cookie.indexOf("=");
        const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

注意,这段代码有两个限制:

它不会删除设置了HttpOnly标志的cookie,因为HttpOnly标志禁止Javascript访问cookie。 它不会删除已设置为Path值的cookie。(尽管这些cookie会出现在文档中。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=/"); }); })();

据我所知,没有办法对域名上的任何cookie集进行全面删除。如果知道cookie的名称,并且脚本与cookie在同一个域中,则可以清除cookie。

你可以将值设置为空,过期日期设置为过去的某个时间:

var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString(); 

这里有一篇关于使用javascript操作cookie的优秀文章。

这里有一个清除所有路径和所有变体域(www.mydomain.example, mydomain。例等):

(function () {
    var cookies = document.cookie.split("; ");
    for (var c = 0; c < cookies.length; c++) {
        var d = window.location.hostname.split(".");
        while (d.length > 0) {
            var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
            var p = location.pathname.split('/');
            document.cookie = cookieBase + '/';
            while (p.length > 0) {
                document.cookie = cookieBase + p.join('/');
                p.pop();
            };
            d.shift();
        }
    }
})();