localStorage in a Firefox extension

10

I am trying to access the localStorage of a page from a Firefox extension. My understanding is that content gives a reference to the window of the current page. When I try and access the localStorage for the page with content.localStorage, I think I am getting a reference to it. However, when I try content.localStorage.length, I get nothing.

Attached is the code in question.

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);

EDIT#1: More information.

try{
    alert(content.localStorage.getItem('todoData'))
    alert(content.localStorage.length)
} catch (e){
   alert(e)
}

The length is throwing the exception "[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"

localStorage.length works when I have it on a standard web page in Firefox, but content.localStorage.length dose not work from the Firefox extension. Now I'm confused...

javascript
html
firefox-addon
local-storage
asked on Stack Overflow Jan 10, 2011 by Alexis • edited Jan 16, 2011 by Alexis

3 Answers

7

From a Firefox extension, you can access the localStorage object with window.content.localStorage, for example:

var ls = window.content.localStorage;
ls.setItem("myvariable", "myvalue");
var item = ls.getItem("myvariable");

Anything else will give you a "Component not available" error.

As an aside, globalStorage doesn't work this way. You can't use it at all with an extension because the object is only available if it's run from a server.

answered on Stack Overflow Dec 18, 2011 by swmcdonnell • edited Sep 30, 2013 by swmcdonnell
2

Using NsIDOMStorageManager xpcom interface you can get your local storage information.

https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMStorageManager

answered on Stack Overflow Feb 24, 2012 by Benz
0

use content.localStorage.wrappedJSObject.myVariable

answered on Stack Overflow Jun 21, 2011 by Hrishikesh Kale

User contributions licensed under CC BY-SA 3.0