操作cookie

 获取cookie

export function getCookie(name: string) {
    let strCookie = document.cookie; // 获取cookie字符串
    let arrCookie = strCookie.split('; '); // 分割
    // 遍历匹配
    for (let i = 0; i < arrCookie.length; i++) {
        let arr = arrCookie[i].split('=');
        if (arr[0] === name) {
            return arr[1];
        }
    }
    return '';
}

设置cookie

export function setCookie(cname, cvalue, exdays) {
    let d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    let expires = 'expires=' + d.toUTCString();
    document.cookie = cname + '=' + cvalue + '; ' + expires;
}

清除指定域名cookie 若不指定则清除当前域名下指定cookie

export function clearCookie(name) {
    const exp = new Date();
    exp.setTime(exp.getTime() - 1);
    const cval = getCookie(name);
    if (cval != null) {
        document.cookie = name + '=' + cval + ';path=/;domain=' + q1_domain + ';expires=' + exp.toUTCString();
    }
}

清除指定域名下所有cookie 若不指定则清除当前域名下所有cookie

// 清除所有cookie函数
export function clearAllCookie() {
    let date = new Date();
    date.setTime(date.getTime() - 10000);
    let keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (let i = keys.length; i--;) {
            document.cookie = keys[i] + '=0; expire=' + date.toUTCString() + '; path=/';
        }
    }
}

  

 

posted @ 2021-01-19 16:28  文学少女  阅读(115)  评论(0编辑  收藏  举报