-
Notifications
You must be signed in to change notification settings - Fork 5
/
setCookie.ts
59 lines (48 loc) · 1.39 KB
/
setCookie.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const converter = {
read(value) {
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
},
write(value) {
return encodeURIComponent(value).replace(
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
decodeURIComponent,
);
},
};
const defaultAttribute = {
path: '/',
};
/**
* 设置cookie
*/
export function setCookie(key: string, value: string, attributes: any) {
if (typeof document === 'undefined') {
return undefined;
}
const newAttributes = Object.assign({}, defaultAttribute, attributes);
if (typeof newAttributes.expires === 'number') {
newAttributes.expires = new Date(
Date.now() + newAttributes.expires * 864e5,
);
}
if (newAttributes.expires) {
newAttributes.expires = newAttributes.expires.toUTCString();
}
const newKey = encodeURIComponent(key)
.replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)
.replace(/[()]/g, escape);
const newValue = converter.write(value);
let stringifiedAttributes = '';
for (const attributeName in newAttributes) {
if (!newAttributes[attributeName]) {
continue;
}
stringifiedAttributes += `; ${attributeName}`;
if (newAttributes[attributeName] === true) {
continue;
}
stringifiedAttributes += `=${newAttributes[attributeName].split(';')[0]}`;
}
document.cookie = `${newKey}=${newValue}${stringifiedAttributes}`;
return document.cookie;
}