如何使用JavaScript删除当前域的所有cookie ?
当前回答
在测试了多种浏览器中列出的几乎所有方法后,我发现几乎没有一种方法能达到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;
}
}
})();
其他回答
我在这里贡献是因为这个功能将允许您删除所有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))
}
)
}
这里有几个答案没有解决路径问题。我认为:如果你控制了网站,或者它的一部分,你应该知道所有使用的路径。所以你只需要让它删除所有路径上的cookie。 因为我的网站已经有jquery(出于懒惰),我决定使用jquery cookie,但你可以很容易地适应纯javascript的基础上的其他答案。
在这个例子中,我删除了电子商务平台正在使用的三个特定路径。
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;
};
我把。com网站改为。com.br,因为我的网站是多域和多语言的
据我所知,没有办法对域名上的任何cookie集进行全面删除。如果知道cookie的名称,并且脚本与cookie在同一个域中,则可以清除cookie。
你可以将值设置为空,过期日期设置为过去的某个时间:
var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString();
这里有一篇关于使用javascript操作cookie的优秀文章。
我有一些更复杂和面向oop的cookie控制模块。它还包含deleteAll方法来清除所有现有的cookie。请注意,这个版本的deleteAll方法有设置path=/,这会导致删除当前域中的所有cookie。如果你只需要从某些范围删除cookie,你将不得不升级这个方法,我添加动态路径参数到这个方法。
主要有Cookie类:
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 setter方法(Cookie.set)相当复杂,所以我把它分解到其他类中。这里有一个代码:
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;
}
}
你可以通过查看文档得到一个列表。饼干变量。清除它们只是一个循环遍历所有它们并一个一个地清除它们的问题。
推荐文章
- 在数组中获取所有选中的复选框
- 如何为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方法