使用JavaScript清除所有cookie

使用JavaScript清除所有cookie,javascript,cookies,Javascript,Cookies,如何使用JavaScript删除当前域的所有cookie?据我所知,无法全面删除域上的任何cookie集。如果您知道cookie的名称,并且脚本与cookie位于同一域中,则可以清除cookie 您可以将该值设置为空,并将到期日期设置为过去的某个位置: var mydate = new Date(); mydate.setTime(mydate.getTime() - 1); document.cookie = "username=; expires=" + mydate.toGMTString

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

据我所知,无法全面删除域上的任何cookie集。如果您知道cookie的名称,并且脚本与cookie位于同一域中,则可以清除cookie

您可以将该值设置为空,并将到期日期设置为过去的某个位置:

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

使用javascript操作cookie有一个简单的方法。

您可以通过查看document.cookie变量获得一个列表。清除它们只是一个将它们循环并逐个清除的问题。

函数deleteAllCookies(){
function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}
var cookies=document.cookie.split(“;”); 对于(变量i=0;i-1?cookie.substr(0,eqPos):cookie; document.cookie=name+“=;expires=Thu,1970年1月1日00:00:00 GMT”; } }
请注意,此代码有两个限制:

  • 它不会删除设置了
    HttpOnly
    标志的cookie,因为
    HttpOnly
    标志禁用Javascript对cookie的访问
  • 它不会删除使用
    路径设置的Cookie
    值。(尽管这些cookie将出现在
    document.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 + ';';
    }
}
函数从所有路径(名称)中删除Cookie{
//此函数将尝试从所有路径中删除cookie。
var pathBits=location.pathname.split('/');
var pathCurrent='path=';
//首先执行简单的无路径删除。
document.cookie=name+'=;expires=Thu,1970年1月1日00:00:01 GMT;';
对于(变量i=0;i
就像往常一样,不同的浏览器有不同的行为,但这对我来说很有效。
享受。

我想我会分享这个清除cookies的方法。也许它在某些方面对其他人有帮助

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;';
}
var cookie=document.cookie.split(“;”);
对于(变量i=0;i
更简单。更快

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:

for (var it in $.cookie()) $.removeCookie(it);
一班轮 如果您想快速粘贴它

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
函数deleteAllCookies(){
var cookies=document.cookie.split(“;”);
对于(变量i=0;i-1?cookie.substr(0,eqPos):cookie;
document.cookie=name+'=;'+
'到期时间=1970年1月1日星期四00:00:01 GMT;'+
'路径='+'/;'+
'domain='+window.location.host+';'+
'安全=;';
}
}

这里有一个方法可以清除域的所有路径和所有变体中的所有cookie(www.mydomain.com、mydomain.com等):

(函数(){
var cookies=document.cookie.split(“;”);
对于(var c=0;c0){
var cookieBase=encodeURIComponent(cookies[c]。拆分(“;”[0]。拆分(“=”[0])+”=;expires=Thu,01-Jan-1970 00:00:01 GMT;域=”+d.join(“)+”;路径=”;
var p=location.pathname.split('/');
document.cookie=cookieBase+'/';
而(p.length>0){
document.cookie=cookieBase+p.join('/');
p、 pop();
};
d、 移位();
}
}
})();

我发现IE和Edge存在问题。Webkit浏览器(Chrome、safari)似乎更宽容。设置cookie时,请始终将“路径”设置为某物,因为默认设置为设置cookie的页面。因此,如果您尝试在其他页面上使其过期而不指定“路径”,则路径将不匹配,也不会过期。
document.cookie
值不显示cookie的路径或过期时间,因此无法通过查看该值来推断cookie的设置位置

如果需要使不同页面的cookie过期,请将设置页面的路径保存在cookie值中,以便以后可以将其拉出,或始终将
“path=/;”
附加到cookie值中。然后它将从任何页面过期。

这里有一个简单的代码

函数deleteAllCookies(){
var cookies=document.cookie.split(“;”);
对于(变量i=0;i
运行函数
deleteAllCookies()
清除所有cookies。

函数方法+ES6 注意:不处理路径


在对多种风格的cookie测试了多种风格的浏览器中列出的几乎所有方法后,我发现这里几乎没有任何方法可以工作,甚至50%

请根据需要帮我改正,但我要把我的2美分扔到这里。下面的方法分解了所有内容,基本上基于两个设置片段构建cookie值字符串,并包括一步一步地构建
//Delete all cookies
function deleteAllCookies() {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + '=;' +
            'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +
            'path=' + '/;' +
            'domain=' + window.location.host + ';' +
            'secure=;';
    }
}
(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();
        }
    }
})();
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);
}
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}`;
  }, "");
}
;(function() {
    if (!window['deleteAllCookies'] && document['cookie']) {
        window.deleteAllCookies = function(showLog) {
            var arrCookies = document.cookie.split(';'),
                arrPaths = location.pathname.replace(/^\//, '').split('/'), //  remove leading '/' and split any existing paths
                arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ];  //  array of cookie settings in order tested and found most useful in establishing a "delete"
            for (var i in arrCookies) {
                var strCookie = arrCookies[i];
                if (typeof strCookie == 'string' && strCookie.indexOf('=') >= 0) {
                    var strName = strCookie.split('=')[0];  //  the cookie name
                    for (var j=1;j<=arrTemplate.length;j++) {
                        if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
                        else {
                            var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';';  //  made using the temp array of settings, putting it together piece by piece as loop rolls on
                            if (j == 1) document.cookie = strValue;
                            else {
                                for (var k=0;k<=arrPaths.length;k++) {
                                    if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
                                    else {
                                        var strPath = arrPaths.slice(0, k).join('/') + '/'; //  builds path line 
                                        strValue = strValue.replace('{path}', strPath);
                                        document.cookie = strValue;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            showLog && window['console'] && console.info && console.info("\n\tCookies Have Been Deleted!\n\tdocument.cookie = \"" + document.cookie + "\"\n");
            return document.cookie;
        }
    }
})();
document.cookie.split(';').forEach(function(c) {
  document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';
});
var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}
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
}
var cookie_version_control = '---2018/5/11';

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name+cookie_version_control + "=" + (value || "")  + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name+cookie_version_control + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function removeCookie(name) {   
    document.cookie = name+cookie_version_control+'=; Max-Age=-99999999;';  
}
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);
    }
}
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;
    }
}
let mainURL = getMainURL().toLowerCase().replace('www.', '').replace('.com.br', '.com'); // i am a brazilian guy
let cookies = $.cookie();
for(key in cookies){
    // default remove
    $.removeCookie(key, {
        path:'/'
    });
    // remove without www
    $.removeCookie(key, {
        domain: mainURL,
        path: '/'
    });
    // remove with www
    $.removeCookie(key, {
        domain: 'www.' + mainURL,
        path: '/'
    });
};

// get-main-url.js v1
function getMainURL(url = window.location.href){
    url = url.replace(/.+?\/\//, ''); // remove protocol
    url = url.replace(/(\#|\?|\/)(.+)?/, ''); // remove parameters and paths
    // remove subdomain
    if( url.split('.').length === 3 ){
        url = url.split('.');
        url.shift();
        url = url.join('.');
    };
    return url;
};
document.cookie.split(";").forEach(function(c) { 
    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
});
//clearing local storage
localStorage.clear();