如何使用JavaScript删除当前域的所有cookie ?
当前回答
下面的代码将删除当前域内的所有cookie和所有尾随子域(www.some.sub.domain.example, .some.sub.domain。例如,.sub.domain。例如,等等。)
一个单行的香草JS版本(我认为这里唯一一个没有使用cookie.split()):
document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));
这是这一行的一个可读版本:
document.cookie.replace(
/(?<=^|;).+?(?=\=|;|$)/g,
name => location.hostname
.split(/\.(?=[^\.]+\.)/)
.reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
.map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);
其他回答
简单。得更快。
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";
}
document.cookie.split(";").forEach(function(c) {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});
//clearing local storage
localStorage.clear();
我在这里贡献是因为这个功能将允许您删除所有cookie(匹配路径,默认为no-path或\),也包括设置为包含在子域上的cookie
function clearCookies( wildcardDomain=false, primaryDomain=true, path=null ){
pathSegment = path ? '; path=' + path : ''
expSegment = "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"
document.cookie.split(';').forEach(
function(c) {
primaryDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment))
wildcardDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment + '; domain=' + document.domain))
}
)
}
在测试了多种浏览器中列出的几乎所有方法后,我发现几乎没有一种方法能达到50%的效果。
如果需要,请帮忙纠正,但我要在这里发表我的意见。下面的方法分解了所有内容,基本上基于设置部分构建cookie值字符串,并包括路径字符串的一步一步构建,当然从/开始。
希望这对其他人有所帮助,我希望任何批评都能以完善这种方法的形式出现。起初,我想要一个简单的1-liner,因为有些人寻求,但JS cookie是那些不那么容易处理的事情之一。
;(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;
}
}
})();
函数方法+ ES6
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}`;
}, "");
}
注意:不处理路径
推荐文章
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- 令牌身份验证vs. cookie
- JS字符串“+”vs concat方法