The most likely issue is that the window
in your extension is not the window
object you are expecting.
Firefox add-ons generally run in a scope where the global window
and document
objects are not defined (if they are defined depends on how the portion of your code that is currently running was entered). Even if they are defined, they are often not defined as the window
, or document
which you are expecting (the window
/document
of the current tab). You will probably need to obtain a reference to both objects for the most recently accessed window/tab.
If a browser window exists (in some instances you could be running where no browser window exists, yet, e.g. at start-up), you can obtain a reference to the most recent browser window
, document
, and gBrowser
with:
if (window === null || typeof window !== "object") {
//If you do not already have a window reference, you need to obtain one:
// Add/remove a "/" to comment/un-comment the code appropriate for your add-on type.
/* Add-on SDK:
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
//*/
//* Overlay and bootstrap (from almost any context/scope):
var window=Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
//*/
}
if (typeof document === "undefined") {
//If there is no document defined, get it
var document = window.content.document;
}
if (typeof gBrowser === "undefined") {
//If there is no gBrowser defined, get it
var gBrowser = window.gBrowser;
}
If you are running the code in response to an event (e.g. a button command
event), you can obtain the current window
with:
var window = event.view
The lack of having the global window
an document
objects available, or having them reference something other than what you are expecting, is something that many people encounter as a problem when writing Firefox add-ons.
Note: If you are wanting to be natively compatible with multi-process Firefox (Electrolysis, or e10s), then gaining access to the contents of the current document is more complex. There are shims in place which should make your code continue to work with multi-process Firefox for some time, but they may/will eventually go away.
References:
nsIWindowMediator
- Working with windows in chrome code
- SDK: window/utils
- SDK: windows
Large portions of this answer were copied from my earlier answers, including this link and here.