Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firefox extension. How to catch onload event?

So..got scriptable extention for firefox. it's somelika a webspider, written in javascript. what i want to do:

i want it load a page, them do some job, then go to another page (using an url from the loaded page). After the new page is loaded - the spider do the same job.

Algoritm is somelike this one:

  1. wait till the page is loaded
  2. do some job
  3. choose a different url
  4. go to this url
  5. goto 1.

in my main function i do this code:

gBrowser.addEventListener("DOMContentLoaded",haXahv8, false); 

and everything works fine till i go to another page...how can i reuse DOMContentLoaded event in my firefox extension? So, the question is: is it possible to reuse load/DOMContentLoaded event in firefox extention for different pages? if yes then how?

p.s.\earlier i was solving this prob,em with windows forms and webbrowser + c++...ooh, what the time it was...a dream! cause everything worked fine=)

like image 641
lazybob Avatar asked Dec 31 '09 02:12

lazybob


2 Answers

You should only have to register for the event once, and you should receive it every time a browser tab fires it.

Your code should work just fine, provided you are waiting for the XUL window to fire its load event before adding an event listener to the gBrowser element. If you are adding an event listener before that, gBrowser is not yet initialized, and the behavior is undefined.

Here is an example:

window.addEventListener('load', function () {
    gBrowser.addEventListener('DOMContentLoaded', function () {
        // stuff that happens for each web page load goes here
    }, false);
}, false);

Note that in practice I can only be sure this works with Firefox 3.5 and up. I wrote an extension (internal to my company) that does this sort of thing reliably for Firefox 1.5 through 3.5, but it is unfortunately a bit more complicated (and fortunately) much more robust than the solution above. If you need support for more than Firefox 3.5+, let me know and I'll provide more info.

Here is some additional reading:

  • https://developer.mozilla.org/en/Code_snippets/On_page_load
  • https://developer.mozilla.org/en/Code_snippets/Tabbed_browser
  • https://developer.mozilla.org/en/Listening_to_events_on_all_tabs
like image 131
Mike Avatar answered Oct 05 '22 13:10

Mike


The last parameter of the addEventListener() method which in your case is set to "false" needs to be set to true, this tells the browser to fire your eventhandler every time the event takes place.

The current value false tells it only to fire your handler the first time the event takes place.

Hope i save some of you out there some time, it took me quite a while searching through the Document Object Model Events pages on W3C.org!

like image 44
Brian Heese Avatar answered Oct 05 '22 12:10

Brian Heese