Search code examples
javascriptfirefoxfirefox-addon-sdkmozillajpm

{jpm} How to replace any page to own?


How can I replace any page e.g http://google.com/ to my page (I don't want to redirect) including <head>?

I tried this:

// Import the page-mod API
var pageMod = require("sdk/page-mod");

// Create a page-mod
// It will run a script whenever a ".io" URL is loaded
// The script replaces the page contents with a message
pageMod.PageMod({
  include: "*.io",
  contentScript: 'document.body.innerHTML = ' +
                 ' "<h1>Page matches ruleset</h1>";'
});

But this doesn't replace the whole page. I want to replace head too. I want to replace the page before the page is loaded...


Solution

  • Using document.head.innerHTML you can refer to the header of the html page, allowing to set the content in it.

    Also worth noting that the page-mod API can take multiple arguments as an array of string literals, as well as being able to import scripts from the data directory.

    And finally, you can set the script to run before the page has loaded by setting the page-mod Option contentScriptWhen to a value of start or ready.

    as per the documentation:

    "start": Load content scripts immediately after the document element is inserted into the DOM, but before the DOM content itself has been loaded

    "ready": Load content scripts once DOM content has been loaded, corresponding to the DOMContentLoaded event

    "end": Load content scripts once all the content (DOM, JS, CSS, images) has been loaded, at the time the window.onload event fires

    So your example for changing both the header and body before the page has loaded would be similar to the below:

    // Import the page-mod API
    var pageMod = require("sdk/page-mod");
    
    // Create a page-mod
    // It will run a script whenever a ".org" URL is loaded
    // The script replaces the page contents with a message
    pageMod.PageMod({
      include: "*.io",
      contentScript: ['document.body.innerHTML = ' +
                     ' "<h1>foo</h1>"',
                     'document.head.innerHTML = ' + 
                     ' "<style>h1 {color:blue;}</style>";'],
      contentScriptWhen: "start"
    });
    

    It's also worth noting that this script may work better for some pages when contentScriptWhen is set to ready, otherwise the changes may not apply to all elements on the page.