JavaScript Singletons in Firefox Add-ons

Occasionally when developing add-ons for Firefox, you want your JavaScript to only run once for the lifetime of the application. Normally, you would place your code in a browser overlay, but this causes the code to run every time a new window is opened. There are several ways to get around this. You could write an XPCOM service or use a JavaScript module. These are both valid methods and work very well if your code is Firefox specific. However, if you are also writing your add-on for Chrome, you might want the code to be able to run in both places. Here is a nice little hack that uses the hidden window so that you can run your Chrome background page within an iframe in Firefox.


  function getBackgroundPage(id, src) {

    // get the firefox hidden window
    var win = Components.classes["@mozilla.org/appshell/appShellService;1"].
                   getService(Components.interfaces.nsIAppShellService).
                   hiddenDOMWindow;

    // if the iframe was previously loaded store it and callback
    var iframe = win.document.getElementsById(id);
    if (iframe)
      return iframe.contentWindow;

    // create the iframe
    iframe = win.document.createElement("iframe");
    iframe.setAttribute("id", id);
    iframe.setAttribute("style", "display:none;");

    // load the source
    iframe.setAttribute("src", src);
    win.document.documentElement.appendChild(iframe);

    // return the content window
    return iframe.contentWindow;

Now you can access your background page by including the script in your overlay and doing:

  var bgp = getBackgroundPage("id for background page", "url of the background page");

** UPDATE **
instead of setting the style to display:none you should instead set the attribute “collapsed” to true. This causes docshell errors in some cases.

iframe.setAttribute(“style”, “display:none;”);
iframe.setAttribute(“collapsed”, “true”);