Padmanathan J
Padmanathan J

Reputation: 4620

Load scripts after page load - Firefox extension

I am creating a Firefox extension. I want load my external js file for all web pages on load time using Firefox extension. I can successfully load all js file on load event in my html file. But how can i execute into my extension.

window.onload = load;
function load() 
{               
      var filerefs=document.createElement('script')
      filerefs.setAttribute("type","text/javascript")
      filerefs.setAttribute("src", 'http://code.jquery.com/jquery-1.9.1.min.js')
      var head = doc.getElementsByTagName( "head" )[ 0 ].appendChild( filerefs );
}

Please guide me.

Upvotes: 4

Views: 4495

Answers (1)

Filipe Silva
Filipe Silva

Reputation: 21657

If you want to detect page load and not application load, you should do it like this (this first part should be in your main overlay file):

// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function (event) {
  // Add a callback to be run every time a document loads.
  // note that this includes frames/iframes within the document

  gBrowser.addEventListener("load", load(event), true);
}, false);

Reference from here

I added the event to the load function because the event fires not only on the load itself, but also on other elements, so you have to validate that you are doing it only once (reference here ):

function load(event) {
    if (event.originalTarget.nodeName == "#document") {
        var htmlns = "http://www.w3.org/1999/xhtml";
        var doc = gBrowser.selectedBrowser.contentDocument;

        var filerefs = doc.createElementNS(htmlns,'script');
        filerefs.setAttribute("type","text/javascript");
        filerefs.setAttribute("src", "http://code.jquery.com/jquery-1.9.1.min.js");
        doc.getElementsByTagName("head")[0].appendChild(filerefs);
    }
}

Instead of using document.getElement..., we have to position on the content of the page, otherwise you are getting elements from your addon (using gBrowser.selectedBrowser.contentDocument gives you access to the current page's dom). And on the createlement, we want to create html elements, so you define and use the html namespace (reference here ).

This should do the trick:

enter image description here

Upvotes: 2

Related Questions