localStorage和cookie操作

localStorage和cookie操作代码:

cookie: {
    isSupportCookie: function() {
        return navigator.cookieEnabled;
    },
    //添加cookie
    add: function(name, value, expires) {
        var storage = window.localStorage;
        if(storage) {
            storage.removeItem(name);
            storage.setItem(name, value);
        } else {
            var str = name + '=' + escape(value);
            if(expires > 0) { //为0时不设定过期时间,浏览器关闭时cookie自动消失
                var date = new Date();
                var ms = expires * 3600 * 1000;
                date.setTime(date.getTime() + ms);
                str += "; expires=" + date.toGMTString();
            }
            document.cookie = str;
        }
        // console.log("添加cookie【" + name + "】成功");
    },
    get: function(name) { //获取指定名称的cookie的值
            try {
                window.localStorage;
            } catch(e) {
                var str = '<img src="./dist/resources/img/tip.jpg"/>'
                var tipDialog = dialog({
                    skin: '_scheduled',
                    title: '提示',
                    content: str,
                    width: 590,
                    button: []
                });
                tipDialog.showModal();
            }
            var storage = window.localStorage;
            if(storage) {
                return storage.getItem(name);
            } else {
                var arrStr = document.cookie.split('; ');
                for(var i = 0; i < arrStr.length; i++) {
                    var temp = arrStr[i].split('=');
                    if(temp[0] == name) {
                        return unescape(temp[1]);
                    }
                }
            }
        }

        ,
    remove: function(name) { //为了删除指定名称的cookie 可以将其过期时间设定为一个过去的时间
        var storage = window.localStorage;

        function del(param) {
            if(storage) {
                storage.removeItem(param);
            } else {
                var date = new Date();
                date.setTime(date.getTime() - 10000);
                document.cookie = param + '=a; expires=' + date.toGMTString();
            }
        }

        if(typeof name === 'object') {
            for(var i = o; i < name.length; i++) {
                del(name[i]);
            }
        } else {
            del(name);
        }
    },
    read: function() { //读取所有保存的cookie字符串
        var str = document.cookie;
        if(str == '') {
            str = "没有保存任何cookie!";
        }
        // console.log(str);
    }
}

 

posted @ 2017-04-28 14:07  Ann丶  阅读(188)  评论(0编辑  收藏  举报