HLJ 发布于
2018-08-12 15:59:24

localStorage/cookie 用法分析与简单封装

本地存储是HTML5中提出来的概念,分localStorage和sessionStorage。通过本地存储,web应用程序能够在用户浏览器中对数据进行本地的存储。与 cookie 不同,存储限制要大得多(至少5MB),并且信息不会被传输到服务器。

什么时候用本地存储?

跨期:不同时间打开页面,比如这次登录需要用到上次登录时保存的数据。
跨页:在同一个浏览器打开同域的多个标签页,它们之间需要互通数据。

选用哪种存储方式?

最简单的数据保存方式就是在js里定义变量并赋值,这不属于本地存储的范畴,但大多数情况下这样做就够了。
cookie的适用场景:数据量小;数据需要随http请求传递到服务端;存储有具体时限的数据;低版本浏览器,不支持localStorage和sessionStorage时。
localStorage的使用场景:数据大于4k;需要跨标签页使用数据;长期存储数据;
sessionStorage的适用场景:数据只在本次会话有效;数据仅在当前标签页有效。sessionStorage对比直接js赋值变量的优势,是可以在同页面跨iframe使用。
浏览器自身会缓存img、js、css等数据,localStorage也可以起到类似作用。

整理本地存储方法

基于localStorage制作一个本地存储插件storage.js,针对只能存字符串、不能设置时限等进行补充,设想:

在不支持localStorage时自动使用cookie
类型转换,可存储数字、布尔、对象等
可设置时限,超时就自我删除
附带整理cookie方法

用法展示:
/** setItem( key, value, time)
 *  key:  键名,字符串
 *  value:键值,可以是Stirng/Boolean/Number/Object等类型
 *  time: 超时时间,非必填,数字型(单位毫秒)。默认长期有效。
 **/
storage.setItem("text", "this is string");
storage.setItem("money", 1234);
storage.setItem("person", {name: "Jone"}, 24*60*60*1000);
 
// getItem 获取值
storage.getItem("money"); //返回数字类型的值1234
 
// removeItem 删除某数据
storage.removeItem("money");
 
// clear 清除所有数据
storage.clear();
 
// 类似方法,操作cookie,只限于存储字符串
storage.setCookie("mycookie", "this is string", 60*60*24*30);
storage.getCookie("mycookie");
storage.removeCookie("mycookie");
storage.clearCookie();
storage.js :
(function(window) {
    var storage = {};
 
    // 是否支持localStorage
    if (!window.localStorage) {
        storage.support = false;
    } else {
        storage.support = true;
    }
 
    // time为超时时间(单位毫秒),非必填
    storage.setItem = function(key, value, time) {
        if (this.support) {
            if (typeof key != "string") {
                console.log("*STORAGE ERROR* key必须是字符串");
                return;
            }
            if (time) {
                if (typeof time != "number") {
                    console.log("*STORAGE ERROR* time必须是数字");
                    return;
                } else {
                    time = parseInt(time) + (new Date()).getTime();
                }
            } else {
                time = null;
            }
            var setValue = {
                value: JSON.stringify(value),
                time: time
            }
            localStorage.setItem(key, JSON.stringify(setValue));
        } else {
            storage.setCookie(key, value, time)
        }
    };
 
    // 不存在的值会返回null
    storage.getItem = function(key) {
        if (this.support) {
            var getValue = JSON.parse(localStorage.getItem(key));
            if (!getValue) {
                return null;
            }
            if (getValue.time && getValue.time < (new Date()).getTime()) {
                localStorage.removeItem(key);
                return null;
            } else {
                return JSON.parse(getValue.value)
            }
        } else {
            storage.getCookie(key)
        }
    };
 
    // 移除某个值
    storage.removeItem = function(key) {
        if (this.support) {
            localStorage.removeItem(key);
        } else {
            storage.removeCookie(key)
        }
    };
    // 清空存储
    storage.clear = function() {
        if (this.support) {
            localStorage.clear();
        } else {
            storage.clearCookie();
        }
    };
 
    /**** cookie方法 ****/
    storage.setCookie = function(key, value, time) {
        if (typeof key != "string") {
            console.log("*STORAGE ERROR* key必须是字符串");
            return;
        } else {
            if (typeof time != "number") {
                // cookie默认存365天
                time = 365 * 24 * 60 * 60 * 1000;
            }
            var d = new Date();
            d.setTime(d.getTime() + time);
            document.cookie = key + "=" + value + "; expires=" + d.toGMTString();
        }
    };
    storage.getCookie = function(key) {
        var cookies = document.cookie.split(";")
        var cookieValue;
        for (var i = 0; i < cookies.length; i++) {
            if (key == cookies[i].split("=")[0]) {
                cookieValue = cookies[i].split("=")[1];
                break;
            }
        }
        return cookieValue;
    };
    storage.removeCookie = function(key) {
        document.cookie = key + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    };
    storage.clearCookie = function() {
        var cookies = document.cookie.split(";")
        for (var i = 0; i < cookies.length; i++) {
            document.cookie = cookies[i].split("=")[0] + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
        }
    };
 
    window.storage = storage;
})(window)

文章来源:网络
最后生成于 2023-06-18 18:29:28
此内容有帮助 ?
0