Clearing all cookies with JavaScript
如何使用JavaScript删除当前域的所有cookie?
1 2 3 4 5 6 7 8 9 10 | 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"; } } |
请注意,此代码有两个限制:
-
它不会删除设置了
HttpOnly 标志的cookie,因为HttpOnly 标志会禁用Javascript对cookie的访问。 -
它不会删除使用
Path 值设置的cookie。 (尽管事实是这些cookie将出现在document.cookie 中,但是如果不指定与设置它相同的Path 值,则无法删除它。)
一支班轮
如果您想快速粘贴...
1 | document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/,"").replace(/=.*/,"=;expires=" + new Date().toUTCString() +";path=/"); }); |
还有一个bookmarklet的代码:
1 | javascript:(function(){document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/,"").replace(/=.*/,"=;expires=" + new Date().toUTCString() +";path=/"); }); })(); |
在对此感到沮丧之后,我将这个函数组合在一起,它将尝试从所有路径中删除一个已命名的cookie。只需为您的每个cookie调用它,您应该比以前更接近删除每个cookie。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 + ';'; } } |
一如既往,不同的浏览器具有不同的行为,但这对我有用。
请享用。
这是清除域的所有路径和所有变体(www.mydomain.com,mydomain.com等)中的所有cookie的一种方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | (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(); } } })(); |
如果您有权访问jquery.cookie插件,则可以通过以下方式清除所有cookie:
1 | for (var it in $.cookie()) $.removeCookie(it); |
据我所知,没有办法彻底删除域上设置的任何cookie。如果您知道名称,并且脚本与cookie在同一个域中,则可以清除cookie。
您可以将值设置为空,将到期日期设置为过去的某个时间:
1 2 3 | var mydate = new Date(); mydate.setTime(mydate.getTime() - 1); document.cookie ="username=; expires=" + mydate.toGMTString(); |
这里有一篇很棒的文章介绍了如何使用javascript处理cookie。
更简单快点。
1 2 3 4 5 | 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"; } |
受第二个答案和W3Schools影响的答案
1 2 3 | document.cookie.split(';').forEach(function(c) { document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;'; }); |
似乎正在工作
编辑:哇几乎与Zach有趣的堆栈溢出如何使它们彼此相邻完全相同。
编辑:显然是临时的nvm
想通了,我会分享这种清除Cookie的方法。在某些时候也许对其他人有帮助。
1 2 3 4 5 6 7 8 9 10 | 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;'; } |
我有一些更复杂且面向OOP的cookie控制模块。 它还包含
主要的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 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); } } |
Cookie设置方法(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 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; } } |
我不知道为什么第一次投票的答案对我不起作用。
正如这个答案所说:
There is no 100% solution to delete browser cookies.
The problem is that cookies are uniquely identified by not just by their key"name" but also their"domain" and"path".
Without knowing the"domain" and"path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!
所以我的想法是添加一个具有完整设置,获取和删除cookie的Cookie版本控件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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;'; } |
您可以通过查看document.cookie变量来获取列表。清除所有内容仅是遍历所有内容并逐一清除它们。
功能方法+ ES6
1 2 3 4 5 6 7 | 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}`; },""); } |
Note: Doesn't handle paths
这是删除JavaScript中所有cookie的简单代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); } |
运行功能
在对多种样式的Cookie进行多种样式的浏览器中列出的几乎所有方法的测试之后,我发现这里几乎没有任何方法可用,甚至50%。
请根据需要帮助纠正,但我要在这里扔2美分。以下方法将分解所有内容,并基本上基于这两个设置片段来构建cookie值字符串,并包括以
希望这对其他人有帮助,我希望任何批评都可以以完善这种方法的形式出现。最初,我想要一个简单的1-liner,就像其他一些人所追求的一样,但是JS cookie是其中一件不那么容易处理的事情。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | ;(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(" \tCookies Have Been Deleted! \tdocument.cookie = "" + document.cookie +"" "); return document.cookie; } } })(); |
jQuery:
1 2 3 4 | var cookies = $.cookie(); for(var cookie in cookies) { $.removeCookie(cookie); } |
香草JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //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=;'; } } |
我在IE和Edge中发现了问题。 Webkit浏览器(Chrome,Safari)似乎更为宽容。设置cookie时,请始终将"路径"设置为某些内容,因为默认设置为设置cookie的页面。因此,如果您尝试在未指定"路径"的情况下在其他页面上使它过期,则该路径将不匹配,并且也不会过期。
如果您需要使不同页面上的cookie失效,请将设置页面的路径保存在cookie值中,以便以后将其拉出或始终将