Page load event detection in Firefox

I am writing a Firefox add-on that does something after the web page is fully loaded.
My current code

var target = this; const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP; const STATE_IS_WINDOW = Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW; const STATE_IS_DOCUMENT = Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT; const locationChangeListener = { onStatusChange: function(){}, onProgressChange: function(){}, onLocationChange: function(aWebProgress, aRequest, aLocation){}, onStateChange: function(aWebProgress, aRequest, aFlag, aStatus){ if((aFlag & STATE_STOP) && (aFlag & STATE_IS_WINDOW)){ //Do something in here } }, onSecurityChange: function(){} }; gBrowser.addProgressListener(locationChangeListener); 

It works great. But sometimes, for example, a web page with an AJAX call, this event was fired several times for one web page.

Is there a way to detect if a webpage is fully loaded or not?

+4
source share
1 answer

If you are only interested in detecting when the page is fully loaded, and not in the intermediate steps, it is easier to listen to loading events, with something like (code from https://developer.mozilla.org/en/Code_snippets/Tabbed_browser ):

 function examplePageLoad(event) { if (event.originalTarget instanceof HTMLDocument) { var win = event.originalTarget.defaultView; if (win.frameElement) { // Frame within a tab was loaded. win should be the top window of // the frameset. If you don't want do anything when frames/iframes // are loaded in this web page, uncomment the following line: // return; // Find the root document: win = win.top; } } } // do not try to add a callback until the browser window has // been initialised. We add a callback to the tabbed browser // when the browser window gets loaded. window.addEventListener("load", function () { // Add a callback to be run every time a document loads. // note that this includes frames/iframes within the document gBrowser.addEventListener("load", examplePageLoad, true); }, false); ... // When no longer needed gBrowser.removeEventListener("load", examplePageLoad, true); ... 

gBrowser is the global var in the main firefox window (if your code is run from a .xul browser overlay, you should see it). If not (for example, it works in the sidebar), you can get a link to the main window:

 var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem) .rootTreeItem .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow); mainWindow.gBrowser.addEventListener (...) 
+2
source

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


All Articles