In the Firefox add-in, how to resolve the "window is not defined" error when adding an eventlistener to the general browser window?

I am trying to add eventListener to my extension. I want to execute a function every time a tab is active (it is clicked by the user) or loaded.

I tried this:

window.addEventListener("DOMContentLoaded", checkHost(), false);

It gives me an error

Unprepared reference error: window not defined

It makes me write, I can not find examples on the Internet. Please help me.

+2
source share
4 answers

Via current status: http://builder.addons.mozilla.org/package/206579/latest

- Addon-SDK, window - - .

( ), , .

let tabs = require('sdk/tabs');
tabs.on('ready', function (tab) {
  console.log(tab.url + ' is ready!');
});
+1

, window, :

var { viewFor } = require("sdk/view/core");
var window = viewFor(require("sdk/windows").browserWindows[0]);

MDN : https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/windows

+2

eventlistener script, browser.xul:

:

window.addEventListener("DOMContentLoaded", function() {checkHost();}, false);
0

, Firefox - . , window, , , . , JavaScript HTML-. , . , window. HTML- .

nsIWindowMediator. MDN , :

Components.utils.import("resource://gre/modules/Services.jsm");
function forEachOpenWindow(todo)  // Apply a function to all open browser windows
{
    var windows = Services.wm.getEnumerator("navigator:browser");
    while (windows.hasMoreElements())
      todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
}

window /, . window /. SDK Add-on, overlay/bootstrap, , .

Firefox -.

if (window === null || typeof window !== "object") {
    //If you do not already have a window reference, you need to obtain one:
    //  Add a "/" to 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");        
    //*/
}

Alternatively using Services.jsm to access nsIWindowMediator :

/* Overlay and bootstrap:
Components.utils.import("resource://gre/modules/Services.jsm");
//*/
if (window === null || typeof window !== "object") {
    //If you do not already have a window reference, you need to obtain one:
    //  Add a "/" to 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 = Services.wm.getMostRecentWindow("navigator:browser");
    //*/
}
0
source

Source: https://habr.com/ru/post/1546531/


All Articles