function getCookie (name) {
const cookieStr = document.cookie;
let cStart = cookieStr.indexOf(`${name}=`);
let cEnd;
if (cStart !== -1) {
cStart += name.length + 1;
cEnd = cookieStr.indexOf(';', cStart);
if (cEnd === -1) {
cEnd = cookieStr.length;
}
return unescape(cookieStr.slice(cStart, cEnd)) || '';
}
return '';
}
function setCookie (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
return false;
}
var sExpires = '';
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + vEnd;
break;
case String:
sExpires = '; expires=' + vEnd;
break;
case Date:
sExpires = '; expires=' + vEnd.toUTCString();
break;
default:
break;
}
}
if (!sDomain) {
sDomain = location.host === 'example01.com' ? '.example01.com' : '.example02.com'; // eslint-disable-line no-param-reassign
}
document.cookie = encodeURIComponent(sKey) + '=' + encodeURIComponent(sValue) + sExpires + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '') + (bSecure ? '; secure' : '');
return true;
}
// 调用
setCookie('userName', 'Diana' || '', 604800, '/');
getCookie('userName');
Cookie --util
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- /** *设置cookie */ function setCookie(cookieName, cookieVal...
- 什么是session?什么是cookie?session和cookie有什么区别?什么场景适用于session?什...
- cookie: 全称http cookie, 是客户端用来储存数据的方式。优点是兼容性好,缺点是会增加网络流量,容...
- 在进行APP+H5混合开发的时候,一些功能是用native方法实现的,如登陆,一些功能是用H5实现的。所以往往需要...