首页 > 解决方案 > Chrome 在关闭浏览器时清除 localStorage/我的代码中的错误/我完全不理解某些内容

问题描述

我在一个小型 React 应用程序上工作,该应用程序应该将一些数据存储在本地存储中。如果我理解正确,它应该保留它们直到明确下令清除。这篇文章的原因是,虽然应用程序数据完全可以在刷新页面操作中幸存下来,但在关闭/打开 Chrome 后它会消失。

这是创建存储的函数:


export function initGlobalStorage() {

    var Storage = function (options) {
      options = options || {};
      for (var i in options) {
        this[i] = options[i];
      }
    };
    const prefix = window.location.href;

    Storage.prototype = {
      storage: window.localStorage,
      addPrefix: function(key){return (prefix + key); },
      
      set: function (key, value) {
        this.storage.setItem(this.addPrefix(key), JSON.stringify(value));
      },
      get: function (key) {
        return this.storage.getItem(this.addPrefix(key));
      },
      remove: function (key, value) {
        this.storage.remove(key, value);
      },
      clear: function () {
        this.storage.clear();
      },
      key: function (index) {
        return this.storage.key(index);
      },
      each: function (fn) {
        if (typeof fn === "function") {
          for (var i = 0, key; i < this.storage.length; ++i) {
            key = this.storage.key(i);
            fn(this.storage.getItem(key), key, i);
          }
        }
      },
      getAll:function(){
        let result =[];
        for(var key in this.storage){
          if (key.includes(prefix)){result.push(JSON.parse(this.storage.getItem(key)))};
        }
        return result;
      },
      hasItems:function(){
        console.log(this.getAll().length);
        return this.getAll().length? true:false;
      },
    };
  

window.Storage = {
    local: new Storage({ storage: window.localStorage }),
    session: new Storage({ storage: window.sessionStorage }),
  };
};

window.local.href 用于将 localStorage 中的“我的项目”与客户端计算机上可能存在的其他项目区分开来。顺便说一句,目前我只在 localhost 上测试这个应用程序。以下是如何应用上述功能


export function checkSupportForCache() {
  return dispatch => {
    if (storageAvailable('localStorage')) {
      dispatch(cacheSupported());
      console.warn("Storage available");
      initGlobalStorage();
      if (window.Storage.local.hasItems()){
        console.log('Storage contains items');
        dispatch(cacheNotEmpty());  
      }else{
        console.warn("No items in storage");
      }
      

    } else {
      console.warn("Storage not available");
    }
  };
}

storageAvailable('localStorage')是检查特定浏览器中对 localStorage 的支持的功能。正如我所写的,当我刷新页面时,localStorage 仍然存在 - 那么我想代码是可以的。但是当关闭浏览器时会发生什么?我不会有意识地要求采取任何形式的净化行动。难道我不自觉?我检查了 Chrome 设置,没有任何可疑之处。根据主题,我根本什么都不懂吗?也许,只是给我一个提示。

标签: javascriptreactjslocal-storage

解决方案


推荐阅读