JS 实现localStorage、sessionStorage兼容的本地化存储方案

1. JS实现缓存(兼容一些旧版不支持storage的浏览器)

实现思路:

a. 缓存在localStorage或sessionStorage

b. 如果浏览器不支持storage,则将数据存储在DOOM元素中(如input元素)

2. 封装一些基本方法

/**

* 设置缓存值

* @param key 主键

* @param value 值

* @param storageType 缓存类型,{1: sessionStorage , 2: localStorage }

*/

function setStorage(key, value, storageType) {

    if (Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]') {

        value = JSON.stringify(value);

    }

    if (!!storageType && storageType === 1) {

        sessionStorage.setItem(key, value);

    } else {

        localStorage.setItem(key, value);

    }

}

/**

* 获取缓存

* @param key 主键

* @param storageType 缓存类型,{1: sessionStorage , 2: localStorage }

* @param isJSON 是否返回JSON,{true: 返回JSON , false: 返回String }

* @returns {*}

*/

function getStorage(key, storageType, isJSON) {

    var value;

    if (!!storageType && storageType === 1) {

        value = sessionStorage.getItem(key);

    } else {

        value = localStorage.getItem(key);

    }

    if (!!isJSON) {

        try {

            value = JSON.parse(value);

        } catch (err)  {

            console.warn('value is not a JSON string =>', err);

        }

    }

    return value;

}

/**

* 删除缓存

* @param key 主键

* @param storageType 缓存类型,{1: sessionStorage , 2: localStorage }

*/

function removeStorage(key, storageType) {

    if (!!storageType && storageType === 1) {

        sessionStorage.removeItem(key);

    } else {

        localStorage.removeItem(key);

    }

}

3. 最后封装

/**

* 兼容性本地化存储方案封装

* 调用:

* new LocalData().set('xxx', 123)

* new LocalData().get('xxx')

* new LocalData().remove('xxx')

*/

function LocalData() {

    this.hostName = location.hostname ? location.hostname : 'localStatus';

    this.isLocalStorage = !!window.sessionStorage;              // 用于判断sessionStorage是否可用

    this.dataDom = null;

    /**

    * 当window.sessionStorage和window.localStorage不可用,则将数据存在dom节点

    * @param key 主键,由set()或get()方法传入

    * @returns {boolean}

    */

    this.initDom = function (key) {

        if (!this.dataDom) {

            try {

                this.dataDom = document.createElement('input'); // 这里使用hidden的input元素

                this.dataDom.type = 'hidden';

                this.dataDom.style.display = 'none';

                this.dataDom.setAttribute('id', key);

                document.body.appendChild(this.dataDom);

                return true;

            }catch (err) {

                return false;

            }

        }else {

            return true;

        }

    };

    /**

    * 存储

    * @param key 主键

    * @param value 值

    * @param storageType 缓存类型,{1: sessionStorage , 2: localStorage }, 默认为1

    */

    this.set = function (key, value, storageType = 1) {

        if (this.isLocalStorage) {

            setStorage(key, value, storageType);

        }else {

            if (this.initDom(key)) {

                if (Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]') {

                    value = JSON.stringify(value);

                }

                this.dataDom.value = value;

            }

        }

    };

    /**

    * 获取

    * @param key 主键

    * @param storageType 缓存类型,{1: sessionStorage , 2: localStorage }, 默认为1

    * @param isJSON 是否返回JSON,{true: 返回JSON , false: 返回String }, 默认为true

    * @returns {string | *}

    */

    this.get = function (key, storageType = 1, isJSON = true) {

        if (this.isLocalStorage) {

            return getStorage(key, storageType, isJSON);

        }else {

            if (this.initDom(key)) {

                var value = this.dataDom.value;

                if (isJSON) {

                    try {

                        value = JSON.parse(value);

                    }catch (err) {

                        console.warn('value is not a JSON string =>', err);

                    }

                }

                return value;

            }

        }

    };

    /**

    * 删除存储

    * @param key 主键

    * @param storageType 缓存类型,{1: sessionStorage , 2: localStorage }

    */

    this.remove = function (key, storageType) {

        if (this.isLocalStorage) {

            removeStorage(key, storageType);

        }else {

            if (this.initDom(key)) {

                document.body.removeChild(this.dataDom);

                this.dataDom = null;

            }

        }

    };

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,219评论 0 2
  • // +-----------------------------------------------------...
    Robinbing阅读 1,527评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,173评论 19 139
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 8,224评论 2 17
  • 打卡。 瑜伽画人任务顺利完成。 专业书看了两篇文章,认真逐字研读,用心记重要的内容,记忆效果一般,所以这种学习要用...
    云小5阅读 234评论 0 0

友情链接更多精彩内容