Detecting page loads in a Firefox Extension

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.

4 thoughts on “Detecting page loads in a Firefox Extension”

  1. 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!

Leave a Reply