Detecting page loads in a Firefox Extension
Posted: September 15th, 2008 | Author: Tim | Filed under: coding, firefox extensions | Tags: addeventlistener, detecting, event, Firefox Extension, gbrowser, page loads | 1,207 Comments »Detecting page loads is a useful ability. It’s easy enough to throw in a
gBrowser.addEventListener(“load”, function_name, true);
But, it causes extra events to get generated. There’s load events occurring in the browser that aren’t page loads. The trick to detecting real page loads (but not Back/Forward navigation when the page is still in memory — only page loads that have a server hit) is to look at the event’s target. In this example, “event” has been passed into the function specified in the addEventListener call above.
if(event.originalTarget instanceof HTMLDocument) {
will make sure that the load event came from a web page being loaded. You can even go a step further and filter out different types of HTMLDocuments.
if(event.originalTarget.defaultView.frameElement) {
will catch events that were triggered as the result of a frame or iframe. It’s an important step, because lots of advertising networks embed their ads in iframes, and you probably are more interested in the actual web page than the ads on that page.
[...] because this is what you want. You wait for the “load” event to fire, and then run your function. Test this code out, and it will work well-enough, most of the time. Sometimes, it lags, sometimes it doesn’t even fire at all. WTF? Well, I’ve been there. [...]
Thanks man! I was looking for such simple, and working explanation for quite some time. At least theres someone in net that know how to post short and usefull info.
Thanks again!