赞
踩
因为名值对可能出现非英文字符,所以使用encodeURIComponent
函数进行编码
const set = (name, value, { maxAge, domain, path, secure } = {}) => { let cookieText = `${encodeURIComponent(name)} = ${encodeURIComponent(value)}`; if (typeof maxAge === 'number') { cookieText += `; max-age=${maxAge}`; } if (domain) { cookieText += `; domain=${domain}`; } if (path) { cookieText += `; path=${path}`; } if (secure) { cookieText += `; secure`; } document.cookie = cookieText; };
使用split
函数将Cookie字符串拆分成数组,最后提取到name和value
使用decodeURIComponent
对值进行解码
const get = name => {
name = `${encodeURIComponent(name)}`;
const cookies = document.cookie.split('; ');
for (const item of cookies) {
const [cookieName, cookieValue] = item.split('=');
if (cookieName === name) {
return decodeURIComponent(cookieValue);
}
}
return;
};
当max-age设置成非正数时,视为删除Cookie
const remove = (name, { domain, path } = {}) => {
set(name, '', { domain, path, maxAge: -1 });
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。