封裝操作cookie的方法

hover_lew發表於2019-02-16

使用原生方法對cookie操作是有些麻煩的,我們可以將其封裝起來,name代表鍵名,value代表值,不填則為讀取名為name的值,option代表設定值如有效期等。其中有效期單位為天。

function cookie(name, value, options) {
        if (typeof value != `undefined`) {
            options = options || {};
            //如果值為null, 刪除cookie
            if (value === null) {
                value = ``;
                options = {
                    expires: -1
                };
            }
            //設定有效期
            var expires = ``;
            if (options.expires && (typeof options.expires == `number` || options.expires.toGMTString)) {
                var date;
                if (typeof options.expires == `number`) {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = `;expires=` + date.toGMTString();
            }
            var path = options.path ? `;path=` + (options.path) : ``;
            var domain = options.domain ? `;domain=` + (options.domain) : ``;
            var secure = options.secure ? `;secure` : ``;
            //設定cookie
            document.cookie = [name, `=`, encodeURIComponent(value), expires, path, domain, secure].join(``);
        } else {
            //讀取cookie
            if (document.cookie.length > 0) {
                var start = document.cookie.indexOf(name + "=")
                if (start != -1) {
                    start = start + name.length + 1;
                    var end = document.cookie.indexOf(";", start);
                    if (end == -1){
                        end = document.cookie.length;
                    }
                    return decodeURIComponent(document.cookie.substring(start, end));
                }
            }
            return ""
        }
    }

    cookie("name", "zhangsan"); //新增name=zhangsan
    cookie("name", null); // 刪除name
    cookie("age", "10", {
        expires: 30
    }); // 新增age=10且有效期30天

相關文章