Firefox扩展中的localStorage

Ale*_*xis 9 javascript html5 firefox-addon local-storage

我试图从Firefox扩展访问页面的localStorage.我的理解是content提供window对当前页面的引用.当我尝试访问该页面的localStorage时content.localStorage,我想我正在获取它的引用.但是,当我尝试时content.localStorage.length,我什么都没得到.

附件是有问题的代码.

var myExtension = {
    init: function() {
        var appcontent = document.getElementById("appcontent");   // browser
        if(appcontent)
            appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
    },

    onPageLoad: function(aEvent) {
        var doc = aEvent.originalTarget;
        alert(content.localStorage) // alerts "[object XPCNativeWrapper [object Storage]]"
        alert(content.localStorage.length) // alerts nothing
    }
window.addEventListener("load", function() { myExtension.init(); }, false);
Run Code Online (Sandbox Code Playgroud)

编辑#1:更多信息.

try{
    alert(content.localStorage.getItem('todoData'))
    alert(content.localStorage.length)
} catch (e){
   alert(e)
}
Run Code Online (Sandbox Code Playgroud)

长度抛出异常"[Exception ..."组件不可用"nsresult:"0x80040111(NS_ERROR_NOT_AVAILABLE)"

localStorage.length当我在Firefox的标准网页上使用它时,它可以content.localStorage.length工作,但不适用于Firefox扩展.现在我很困惑......

swm*_*ell 7

在Firefox扩展中,您可以使用window.content.localStorage访问localStorage对象,例如:

var ls = window.content.localStorage;
ls.setItem("myvariable", "myvalue");
var item = ls.getItem("myvariable");
Run Code Online (Sandbox Code Playgroud)

其他任何东西都会给你一个"组件不可用"的错误.

顺便说一句,globalStorage不会这样工作.您根本无法使用扩展名,因为该对象仅在从服务器运行时才可用.