I'm developing a Firefox extension and have the following code:
function initialize() {
// For accessing browser window from sidebar code.
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
var gBrowser = mainWindow.gBrowser;
gBrowser.onload = function() {
alert('loaded');
};
}
I use .onload rather than DOMContentLoaded or readystatechange as I need to wait until all other javascript has finished loading on a page before I run mine.
Any ideas as to why multiple events are being triggered (and for things that the event shouldn't be triggered for)?
SOLUTION
Following from MatrixFrog's suggestion, here is the solution I came to:
function initialize() {
// For accessing browser window from sidebar code.
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
var gBrowser = mainWindow.gBrowser;
if (gBrowser.addEventListener) {
gBrowser.addEventListener("load",pageLoaded,true);
}
}
function pageLoaded(aEvent) {
if ((aEvent.originalTarget.nodeName == '#document') &&
(aEvent.originalTarget.defaultView.location.href == gBrowser.currentURI.spec))
{
alert('loaded');
}
}
From https://developer.mozilla.org/en/Code_snippets/On_page_load
Current Firefox trunk nightlies will fire the onPageLoad function for not only documents, but
xul:image
s (favicons in tabbrowser). If you only want to handle documents, ensureaEvent.originalTarget.nodeName == "#document"
If you're still seeing extraneous 'load' events firing, you may want to inspect the event target to figure out what's being loaded, and use similar logic to avoid calling your extension's logic in certain specific cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With