Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

Change html page content


I am creating Firefox addon using the Add-on SDK. I want to get data from remote url and inject it in current html. As of now i m able to fetch data using request module of Firefox addon sdk but m not able to inject it in current page.

for example : i am fetching response from website "abc.com".after fetching response i will augment current page with response

// main.js

var widgets = require("sdk/widget");
var tabs = require("sdk/tabs");
var Request = require("sdk/request").Request;

//create addon widget
var widget = widgets.Widget({
    id: "div-show",
    label: "Show divs",
    contentURL: "http://www.mozilla.org/favicon.ico",
    onClick: function() {
    //initializing request module to fetch content
    quijote.get();
    }
});

//fetch content of requested page
var quijote = Request({
    url: "http://localhost/abc/",
    overrideMimeType: "text/plain; charset=latin1",
    onComplete: function (response) {
        //check if content is fetched successfully 
        addContent(response);
    }
});

//try and modify current page
function addContent(response){
    //initialize page modification module
    var pageMod = require("sdk/page-mod");
    tabs.activeTab.attach({
       contentScript: 'document.body.innerHTML = ' + ' "<h1>'+response.text+'</h1>";'
    });
}

Is their any way in which i can augment my current page???


Solution

  • Your code will bitterly fail e.g. when response.text includes a double quote. Then your code would be (assume it is <a href="hello">world</a>):

    document.body.innerHTML = "<h1><a href="hello">world</a></h1>";
    

    This is obviously invalid code.

    Your code basically constructs a dynamic script from unsanitized data, which is a bad idea because (other than the escaping problem above)

    1. you'll be running an unsanitized content script if that code is even valid and
    2. if that would succeed, the page might run unsanitized code as well.

    This is the web equivalent to SQL injection attacks....

    First, lets tackle 1.) with messaging (more):

    var worker = tabs.activeTab.attach({
       contentScript: 'self.port.on("setdom", function(data) { ' +
                        + 'document.body.innerHTML = data; /* still a security issue! */'
                        + '});'
    });
    worker.port.emit("setdom", response.text);
    

    This guarantees that the content script will be valid (can even run) and does not run arbitrary code.

    However 2.) is still a problem. Read DOM Building and HTML insertion.