0

私はFirefox拡張機能を作成しています。ブラウザ全体のグローバル変数として localStorage を使用したい。ただし、保存されたタブでのみ機能しています。他のタブでこの値を読み取ることができません。任意のタブからアクセスできるようにするにはどうすればよいですか、または考えられる問題は何ですか?

私はそれを次のように使用します:

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

より正確には、ページが読み込まれたときに JavaScript コードをページに挿入しています。挿入されたコードから、値をローカルストレージに保存したいと思います。

タブの URL が異なります。私のコードは、ページがロードされたときにローカルストレージを使用しようとしています。ただし、次のように 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 に答える