我正在尝试从 Firefox 扩展访问页面的 localStorage。我的理解是 content
给出了对当前页面的 window
的引用。当我尝试使用 content.localStorage
访问页面的 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);
编辑#1:更多信息。
try{
alert(content.localStorage.getItem('todoData'))
alert(content.localStorage.length)
} catch (e){
alert(e)
}
长度抛出异常“[Exception...”Component is not available“nsresult:”0x80040111 (NS_ERROR_NOT_AVAILABLE)“
localStorage.length
当我在 Firefox 的标准网页上使用它时有效,但 content.localStorage.length
在 Firefox 扩展中不起作用。现在我很困惑......
最佳答案
从 Firefox 扩展中,您可以使用 window.content.localStorage 访问 localStorage 对象,例如:
var ls = window.content.localStorage;
ls.setItem("myvariable", "myvalue");
var item = ls.getItem("myvariable");
任何其他的都会给你一个“组件不可用”的错误。
顺便说一句,globalStorage 不是这样工作的。您根本不能将它与扩展一起使用,因为该对象只有在从服务器运行时才可用。
关于javascript - Firefox 扩展中的 localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4648645/