I'm having a little bit of trouble managing the load of sites in a Firefox extension.

I'm using JavaScript and developing a Firefox extension to search a string in a list of websites of my own, to look for bad words. The problem is that I am searching the list one by one. That means, I am loading a webpage and I add an event listener to DOMContentLoaded; when the DOM loads a function is called to search for the string. But, if the page does not load (A network issue for example) the function is never called.

Is there a way to set a timer to an event listener? If the event is not triggered in 5 seconds then do something. Or if there is another way to do that please advice! I minimized the code a lot but i think you can get the idea here.

function main_(){
            //do some stuff here and if needed call to open a new page
            waitForDOM();
}

function waitForDOM(){
            //if the list of pages is grather than 0 then
    //add the new tab here and create the event listener
    gBrowser.addEventListener('DOMContentLoaded',pageLoaded,true);
 }

function pageLoaded(aEvent) {
        //do the search here and calls the function waitForDOM to load a new page and a event listener
    waitForDOM();
}
link|improve this question
feedback

2 Answers

up vote 1 down vote accepted

I don't know anything about coding Firefox extensions, but in a general sense you can certainly set a timer to do something if your event handler isn't called within a certain time. Something like this:

var eventTriggeredFlag = false;

function waitForDOM(){
  gBrowser.addEventListener('DOMContentLoaded',pageLoaded,true);
  setTimeout(function(){
               if (!eventTriggeredFlag) {
                  // time's up without the event: do something
               }
             }, 5000);
}

function pageLoaded(aEvent) {
  eventTriggeredFlag = true;
  // whatever else you want to do here...
}

If you need to keep track of multiple events with separate timers you'd obviously have to make that more complicated, perhaps with some closures or an array of events or something.

link|improve this answer
Thanks for this answer, i didnt think of using setTimeout ! A clever approach. – user886869 Aug 12 '11 at 18:55
feedback

It is better to add a progress listener instead of using DOMContentLoaded. The method onStateChange of your progress listener will always be called with STATE_STOP and STATE_IS_WINDOW flags when the page finishes loading - regardless of whether there is an error or not. You can call Components.isSuccessCode(aStatus) to see whether the page loaded successfully (note that this will only report network errors, HTTP errors like 404 will still count as success).

link|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.