CookieVersionContro

2022-5-16 18:48| 发布者: Hocassian| 查看: 86| 评论: 0|原作者: 樱花庄的白猫

摘要:
C:\Users\Administrator\Downloads\2019-10-14-0-25-44-134316815868599-樱花庄的白猫 ねこ・しろ・ましろ-采集的数据-后羿采集器.html

标题

Cookie Version Control

标题链接

https://2heng.xin/2018/05/12/add-a-version-control-for-cookies/

post-date

发布于 2018-05-12

post-meta

5,608 热度

评价数

16 条评论

分类

野生技术协会

正文

Originally posted on my notebook: https://mashiro.top/2018/05/11/add-a-version-control-for-cookies/


When adding some new features to my JavaScript, I find the remaining cookies are pretty hard to deal with that some of them were set by actions such as click and hover. So firstly I considered doing something to clean all cookie at once:

if (getCookie("cookie_control")!="2018/5/11") {
deleteAllCookies();
setCookie("cookie_control","2018/5/11",365);
}

But I found there is no such an easy deleteAllCookies() method!

As this answer said:

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!

So my idea is to add a Cookie version control with a full set of setting, getting and removing of cookies:

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;';
}

Now everytime you want to update your cookies, it's OK just modifying the content of cookie_version_control.

Q.E.D.

作者

Mashiro


路过

雷人

握手

鲜花

鸡蛋

最新评论

返回顶部