zoukankan      html  css  js  c++  java
  • 操作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=/';
            }
        }
    }
    

      

  • 相关阅读:
    Javascript 之 存储
    Javascript 之 跨域
    Javascript 之 Ajax
    Javascript 之 事件
    流程控制语句
    JS属性操作
    JS效果的步骤
    遍历Map的四种方法
    自动删除ftp自动保存的密码
    IE6下png格式透明图片显示灰色的解决办法.
  • 原文地址:https://www.cnblogs.com/Ewarm/p/14298637.html
Copyright © 2011-2022 走看看