0

我正在创建一个 Firefox 扩展。我想使用 localStorage 作为整个浏览器的全局变量。但它仅适用于保存它的选项卡。我无法在其他选项卡中读取此值。我如何使它可以从任何选项卡访问,或者可能存在哪些问题?

我像这样使用它:

localStorage.getItem('variable')
localStorage.setItem('variable','value')

更准确地说,我在页面加载时将 javascript 代码注入到页面中。从注入的代码中,我想将我的值保存到本地存储。

标签有不同的网址。我的代码在页面加载时尝试使用本地存储。但它检查 localStorage 值是否存在,如下所示:

if(localStorage.getItem('variable')){ ... }
4

1 回答 1

-2

我认为您不能localStorage用作全局变量

localStorage is also the same as globalStorage[location.hostname], with the exception 
of being scoped to an HTML5 origin (scheme + hostname + non-standard port) and 
localStorage being an instance of Storage as opposed to 
globalStorage[location.hostname] being an instance of StorageObsolete which is covered 
below. For example, http://example.com is not able to access the same localStorage 
object as https://example.com but they can access the same globalStorage item. 
localStorage is a standard interface while globalStorage is non-standard so you 
shouldn't rely on these.

Please note that setting a property on globalStorage[location.hostname] does not set 
it on localStorage and extending Storage.prototype does not affect globalStorage 
items, only extending StorageObsolete.prototype does.

考虑使用globalStorage,然后localStorage在需要的地方设置。

来源:https ://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage#localStorage

于 2013-05-23T18:51:19.657 回答