javascript - 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 设置,没有任何可疑之处。根据主题,我根本什么都不懂吗?也许,只是给我一个提示。
解决方案
推荐阅读
- c++ - 在 std::uint8_t 中移位
- google-cloud-stackdriver - 谷歌云中项目删除操作的日志
- c# - 如何将 Azure Active Directory 身份验证添加到 .Net Core 静态页面作为团队个人选项卡
- multithreading - 我应该对 Camel Enpoint URI 中的选项进行 url 编码吗
- c++ - C++中的cout问题
- c - C sscanf i386 与 x86_64 解析引用字符串的不同行为
- javascript - 无法在 JavaScript 函数中检索 ASP.Net 文本框值
- android - 这个 Android 元素的名称是什么?
- python - 使用res从python中的列表中提取一组序列不会产生预期的结果
- mysql - 如果不为空,则在可能的其他 id 上加入 MySQL