Search code examples
javascriptdialogevent-handlingfirefox-addondom-events

Issues with "load" event handler in Firefox Extension Developement


I'm writing a Firefox extension, but have issues with user interaction because of getting the right events properly. My extension shall complete the following tasks:

  • check the currently viewed browser tab on certain structures
  • do some backend server calls
  • open dialog
  • redirecting the user to a landing page

So far so good, it works. I start the sequence with the following eventHandler:

window.gBrowser.selectedTab.addEventListener("load",function(){ Fabogore.Load();},true);

after opening the dialog, I try to remove the EventHandler from within the Dialog:

window.opener.gBrowser.selectedTab.removeEventListener("load",function(){Fabogore.Load();},true);

But the sequence gets triggered again and again, the eventlistener fetches every load event of every single tab, although i used the selectedTab? So the Dialog pops up again and again. I've also tried closing the event Handler in the original Javascript.

Any guesses?


Solution

  • This is easily explained - the function you add as a listener and the function you remove are different. Try running this code:

    alert(function(){ Fabogore.Load();} == function(){ Fabogore.Load();});
    

    This will show you false, each time you define a function in your code a new function is created. To solve your problem you need to define one function, store the reference to it and use it both to add and remove the listener:

    var listener = function(){ Fabogore.Load();};
    var listenerTab = window.gBrowser.selectedTab;
    listenerTab.addEventListener("load", listener, true);
    [...]
    listenerTab.removeEventListener("load", listener, true);
    

    Note that I also stored the value of window.gBrowser.selectedTab in a variable - by the time you decide to remove your listener the selected tab might change already. You want to remove the listener from the tab you added it on and not some other tab.