使用js操作浏览器cookie的设置,读取,删除
# 1、设定指定cookie值
const setCookie = (key, value, t) => {
let oDate = new Date();
oDate.setDate(oDate.getDate() + t);
document.cookie = key + "=" + value + "; expires=" + oDate.toDateString();
}
1
2
3
4
5
2
3
4
5
# 2、获取指定cookie值
const getCookie = (name) => {
let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) return unescape(arr[2]);
return null;
}
// 或者
const getCookie = (key) => {
let arr1 = document.cookie.split("; ");//由于cookie是通过一个分号+空格的形式串联起来的,所以这里需要先按分号空格截断,变成[name=Jack,pwd=123456,age=22]数组类型;
for (let i = 0; i < arr1.length; i++) {
let arr2 = arr1[i].split("=");//通过=截断,把name=Jack截断成[name,Jack]数组;
if (arr2[0] == key) {
return decodeURI(arr2[1]);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 3、移除指定cookie值
const removeCookie = (key) => {
setCookie(key, "", -1);//把cookie设置为过期
}
1
2
3
2
3
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13