# 读取cookie
document.cookie
能读取到非httpOnly的cookie, 返回一个字符串, 类似name=richard; age=18
function parseCookie() {
const cookie = document.cookie;
const reg = /(\w+)=(\w+);?/g;
let result = {};
cookie.replace(reg, (match, key, value) => {
result[key] = value;
});
return result;
}
function getCookie(name) {
return parseCookie()[name]
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 设置/修改cookie
document.cookie="name=richard; path=/; expires=Tue, 14 Jan 2020 08:32:36 GMT"
; 其中expires是Date对象toGMTString方法返回的字符串
WARNING
cookie不能设置非法字符, 例如空格, 分号这些, document.cookie="name=ricahrd li"
, 最后的结果是只能设置成为richard, 空格后的字符被忽略了
function setCookie(name, value, {path, expires} = {}) {
let cookie = `${name}=${value}`;
if(path) {
cookie += `; path=${path}`;
}
if(expires) {
cookie += `; expires=${new Date(expires).toGMTString()}`;
}
console.log("set cookie: " + cookie);
document.cookie = cookie;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 删除cookie
本质也是修改cookie, 原理是把cookie的expires属性设置成一个过去的时间
function removeCookie(name) {
setCookie(name, "", {expires: new Date(0)})
}
1
2
3
2
3