本地存储是否持久?
我正在使用本地存储作为 Chrome 扩展程序。当我使用...设置本地存储
localStorage['tracking'] = false;
,然后检查是否使用本地存储设置:
if(localStorage['tracking'])
{
alert('set');
} else {
alert('Not Set');
localStorage['tracking'] = true;
}
它工作正常。如果未设置并保持设置状态,则它将跟踪设置为 true。但是,如果我转到一个新选项卡,并转到我在另一个选项卡中所在的同一页面,它将返回未设置的状态。
即使在浏览器关闭后,是否有任何方法可以使本地存储保持持久性?
编辑:如果脚本,我不会在顶部设置 localStorage 数组元素。刚刚意识到这可能会让读者感到困惑。
I'm using Local Storage for a Chrome extensions. When I set the local storage using
localStorage['tracking'] = false;
... and then check to is local storage set using:
if(localStorage['tracking'])
{
alert('set');
} else {
alert('Not Set');
localStorage['tracking'] = true;
}
It works fine. It sets tracking to true if unset and remains set. But if I go to a new tab, and to the same page I was on in the other tab, it returns unset.
Is there any way for local storage to remain persistant, even after the browser has closed?
Edit: I am not setting the localStorage array element at the top if the script. Just realised that might confuse readers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试:
这些
是 W3C API 规范 中使用的方法。
由于未指定您提到的用法,因此根据浏览器实现,您可能会向当前
window
对象中的localStorage
全局变量添加新属性,该属性将变得不可用当离开页面时。Try:
and
These are the methods used in the W3C API Specification.
Since the usage you mentioned is not specified, depending on browser implementation it is possible that you are adding new properties to the
localStorage
global variable in the currentwindow
object, which become unavailable when navigating away from the page.LocalStorage 仅适用于字符串。检查此解释。
LocalStorage works only with strings. Check this explanation.
我曾经也有同样的问题。我想分享我的解决方案。不过,我的情况可能和你的情况不一样。
我的情况是,我在内容脚本中有此代码 (localStage['xxxx']='xxx';)。然后我在打开新选项卡或打开新窗口时遇到问题。
所以,我的解决方案是我没有直接通过内容脚本运行此代码。内容脚本将调用“chrome.extension.sendRequest”,background.html 将设置/读取 localStrage 并返回到内容脚本。
这将是内容脚本中的代码
这将是background.html 中的代码。
I used to have the same problem. I would like to share my solution. However, my case may not be the same as your case.
My case ist that I had this code (localStrage['xxxx']='xxx';) in a content script. Then I had the problem when open the new tab or open new windows.
So, my solution is that I did not run this code by the content script directly. The content script will call 'chrome.extension.sendRequest' and the background.html will do set/read localStrage and return to the content script.
This will be the code in content script
This will be the code in background.html.