Cookie相关

操作Cookie相关内容。

获取Cookie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 获取cookie
*
* @export
* @param {string} coockiename
* @return {*} {(string | undefined)}
*/
export function getCookieValue(coockiename: string): string | undefined {
try {
const name = coockiename + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
const c = ca[i].trim();
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
} catch (e) {}
return undefined;
}

设置Cookie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 设置cookie
*
* @export
* @param {string} name
* @param {string} val
* @param {number} [expTime=365]
*/
export function setCookieValue(name: string, val: string, expTime = 365) {
// 默认cookie有效期365天, 严格设置GTM格式
const exp = new Date(Date.now() + expTime * 864e5);
document.cookie = `${name}=${encodeURIComponent(
val
)};expires=${exp.toUTCString()}; path=/; domain=${getCookieDomain()};`;
}

获取主域名

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
/**
* 获取主域名,如果域名是ip,直接返回 eg:www.baidu.com => .baidu.com
* @export
* @param {string} [hostName]
* @return {*} {string}
*/
export function getCookieDomain(hostName?: string): string {
const initialHost: string = hostName || location.hostname;
let host: string = initialHost;

const ip =
/^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$/;

if (ip.test(initialHost) === true || initialHost === 'localhost') return initialHost;

const regex = /([^]*).*/;
const match: RegExpMatchArray | null = initialHost.match(regex);

if (match !== undefined && match !== null) host = match[1];

if (host !== undefined && host !== null) {
const strAry: string[] = host.split('.');
if (strAry.length > 2) {
host = strAry.slice(1).join('.');
}
}
return `.${host}`;
}
------本文结束 感谢阅读------