Jacques Blom
Jacques Blom

Reputation: 1822

The equivalent to a content script in a Firefox extension?

I am quite new to Firefox and its extensions. Is there something like a script using JavaScript that runs every time a page loads? My chrome extension injects a css file creating a link tag using js. How do I port this to Firefox?

Upvotes: 5

Views: 3275

Answers (3)

abraham
abraham

Reputation: 47913

You want the pageMod API.

var pageMod = require("page-mod");
pageMod.PageMod({
  include: "*.example.org",
  contentScript: 'window.alert("Page matches ruleset");'
});

Upvotes: 7

Alejandro Silvestri
Alejandro Silvestri

Reputation: 3784

I used to use Greasemonkey on Firefox. In fact, Chrome Extensions began as a mimic of Greasemonkey, and were the origin of content scripts.

Upvotes: 0

Hemant Pawar
Hemant Pawar

Reputation: 360

You can use mozIJSSubScriptLoader to execute the JavaScript (chrome://myExtension/content/script.js) every time a webpage loads. Here is the sample code that you need to modify according to your chrome directory

window.addEventListener("load", function load(event){
    window.removeEventListener("load", load, false); //remove listener, no longer needed
    myExtension.init();  
},false);

var myExtension = {
  init: function() {
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent){
      appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
    }
    var messagepane = document.getElementById("messagepane"); // mail
    if(messagepane){
      messagepane.addEventListener("load", function(event) { myExtension.onPageLoad(event); }, true);
    }
  },

  onPageLoad: function(aEvent) {
    var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
    // do something with the loaded page.
    // doc.location is a Location object (see below for a link).
    // You can use it to make your code executed on certain pages only.
    var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
              loader.loadSubScript("chrome://myExtension/content/script.js", doc); 

    // add event listener for page unload 
    aEvent.originalTarget.defaultView.addEventListener("unload", function(event){ myExtension.onPageUnload(event); }, true);
  },

  onPageUnload: function(aEvent) {
    // do something
  }
};

Upvotes: 0

Related Questions