Cookie --util

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');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容