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
.
「樱花庄的白猫」原创文章:《Cookie Version Control》,转载请保留出处!https://2heng.xin/2018/05/12/add-a-version-control-for-cookies/
Q.E.D.
Comments | 25 条评论
这个主题真好看……
我想问的是每个文顶部都有一张图是怎么搞的
@啾妮的啊网 文章编辑页添加特色图
请问下屏幕左下角这个动漫小人怎么弄的啊,好萌好想要一个!!!
@Becase 插件搜索Live 2D。不过博主这个应该增加了自定义化,多了些模型和功能
特别想知道这个鼠标是怎么弄的,想学习学习搞一个类似的兔子
点赞,非常棒的开源主题
6666
这代码的样式非常好看,很喜欢这种简洁大气的风格。
有点蒙蔽中
@1322546902 xin chǎo
@1322546902 xin chǎo
向大佬学习。
白喵的小站越来越好看了,每次进来都能发现许多新的小彩蛋
,可以说是目前看到的最好看的主题了,好吧,之一
(=・ω・=)
@蝉時雨 比不上大佬你的
前天刚把主题开源了
(`・ω・´)
@Mashiro 我的就是几天时间的练手速成品,坑多的一匹,懒癌发作起来坑都不想填,虽然有很多想法但是不想干

白喵主题做得这么好,我都想用回 wordpress 了
@蝉時雨 记得你的博客好像是 React 构建的是吗?最近想入坑框架,打算用 Django 做后端,React 或者 Vue 做前端,小白不知道这是个好主意吗?
@Mashiro 如果要用 React 的话就要好好考虑 SEO 了,需要做服务端渲染,我没做过,毕竟我连服务器都没有,不过应该能找到成熟的方案(之前看过)
。
@蝉時雨 啊,好的,我先踩踩坑,大佬请多多指教
该评论为私密评论