js存取Cookie

68次阅读

共计 3544 个字符,预计需要花费 9 分钟才能阅读完成。

js 存取 Cookie

在采用正则表达式匹配时出现匹配出现但是为 false 的情况:

解决:

正则匹配全局后 lastIndex会加 1,下一次匹配会变成从第二位开始,而你 test 里面只有 1 位,所以匹配失败,匹配失败后 lastIndex 会变成 0,再下一次匹配从第一位开始,匹配成功 …..
要么去掉/g,要么手动把reg.lastIndex=0

没有进行 encodeURIComponent 遇到 = 出现解析不全问题

解决:

采用正则表达式 new RegExp(_name + "=([^;]*)(;|$)") 动态去匹配值信息,保证数据的完整性。最后一定要用 () 的方式进行 运算,否则会出现问题。

(function (root, factory) {
    // 处理模块化开发
    if (typeof define === "function" && define.amd) {define([], factory);
    } else if (typeof exports === "object") {module.exports = factory();
    } else {root.pageUtils = factory();
    }
})(this, function () {var owner = {};

    function isRegExp(obj) {return Object.prototype.toString.call(obj) == "[object RegExp]";
    }
    
    function getCookieReg(_name) {return new RegExp(_name + "=([^;]*)(;|$)");
    }

    /**
   * 获取指定名称的 Cookie 值
   * @param {Object} _name
   */
    owner.getCookie = function (_name) {
        var info = document.cookie;
        var cookieArr = info.split(";");

        for (var i = 0, l = cookieArr.length; i < l; i++) {var valueArr = cookieArr[i].split("=");
            if (valueArr[0] && valueArr[0] == _name) {var cookieResults = document.cookie.match(getCookieReg(_name));
                if (cookieResults.length > 1) {
                    try {return JSON.parse(decodeURIComponent(cookieResults[1])).value || JSON.parse(decodeURIComponent(cookieResults[1]));
                    } catch (err) {return decodeURIComponent(cookieResults[1]);
                    }
                } else {return '';}
            }
        }
    }

    /**
   * 获取指定名称的 Cookie 值
   * @param {Object} _name
   */
    owner.getCookieObj = function () {var obj = {};
        var info = document.cookie;
        var cookieArr = info.split(";");

        for (var i = 0, l = cookieArr.length; i < l; i++) {var valueArr = cookieArr[i].split("=");
            if (valueArr[0]) {var cookieResults = document.cookie.match(getCookieReg(valueArr[0]));
                if (cookieResults.length > 1) {
                    try {obj[valueArr[0]] = JSON.parse(decodeURIComponent(cookieResults[1])).value || JSON.parse(decodeURIComponent(cookieResults[1]));
                    } catch (err) {obj[valueArr[0]] = decodeURIComponent(cookieResults[1]);
                    }
                } else {obj[valueArr[0]] = '';
                }
                
            }
        }

        return obj;

    }


    /**
   * 设置 Cookie 信息
   * @param {String} _key
   * @param {String} _value
   * @param {Numer} _expires  单位秒
   * @param {String} _path
   * @param {Boolean} isJsonWarp 是否用 json 包裹
   */
    owner.setCookie = function (_key, _value, _expires, _path, isJsonWarp) {
        _key = _key || "";
        _value = _value || "";
        isJsonWarp = isJsonWarp || false;
        var result = "";

        if (!_key) {return;}

        if (typeof _expires === 'boolean') {isJsonWarp = _expires;} else if (typeof _path === 'boolean') {isJsonWarp = _path;}

        if (isJsonWarp) {
            var jsonObj = {"value": _value};
            result = _key + "=" + encodeURIComponent(JSON.stringify(jsonObj)) + ";";
        } else {result = _key + "=" + encodeURIComponent(_value) + ";";
        }


        // 获取过期时间
        if (typeof (_expires) == "number") {
            // 表示设置为 expires 的值
            // 设置过期时间
            var d = new Date();
            d.setDate(d.getDate() + _expires);
            result += "expires=" + d + ";" + "path=" + _path;
        } else if (typeof (_expires) == "string") {result += "path=" + _expires;}
        document.cookie = result;
    }

    /**
   * 移除指定 Cookie 信息
   * @param {Object} _name
   */
    owner.removeCookie = function (_name) {this.setCookie(_name, "", -1);
    }

    /**
   * 获取开头为指定名称的 Cookie 信息
   * @param {Object} _name 传入的字符串或者是 RegExp
   * @param {Object} callback
   */
    owner.getCookies = function (_name, callback) {
        var info = document.cookie;
        var cookieArr = info.split(";");
        var l = cookieArr.length;
        var getInfoArr = [];
        var regInfo = null;

        if (l > 0) {if (isRegExp(_name)) {regInfo = _name;} else {regInfo = eval("/" + _name + "/g");
            }

            for (var i = 0; i < l; i++) {var valueArr = cookieArr[i].split("=");
                var key = valueArr[0];
                if (regInfo.test(key)) {
                    regInfo.lastIndex = 0;
                    //  正则匹配全局后 lastIndex 会加 1,下一次匹配会变成从第二位开始,而你 test 里面只有 1 位,所以匹配失败,匹配失败后 lastIndex 会变成 0,再下一次匹配从第一位开始,匹配成功.....
                    // 要么去掉 /g,要么手动把 reg.lastIndex=0
                    var value = null;
                    var cookieResults = document.cookie.match(getCookieReg(key));
                    if (cookieResults.length > 1) {
                        try {value = JSON.parse(decodeURIComponent(cookieResults[1])).value || JSON.parse(decodeURIComponent(cookieResults[1]));
                        } catch (err) {value = decodeURIComponent(cookieResults[1]);
                        }
                    } else {value = '';}
                    

                    getInfoArr.push([key, value]);

                    if (callback) {callback(key, value);
                    }
                }
            }
        }
        return getInfoArr;
    }

    return owner;
});

正文完
 0