Forivin
Forivin

Reputation: 15548

Modify websites with Firefox Add-on

I'm writing a Firefox Add-on that modifies some specific websites when I open them. But I don't like the API at all. For example if I want to add a div-container that contains a button to a tab. It would look about like this:

var myScript = 'document.body.innerHTML += "<div style=background-color:rgba(0,0,0,0.5);position:fixed;width:300px;height:300px;right:0px;top:0px;><input type=button value=test></input></div>";';
tab.attach({ contentScript: myScript });

This is:
1. Completely unreadable.
2. Will look different on lots of websites because some websites add default styles to all input-elements.

So is there a more readable way to modify a website that doesn't require to add a script as a string?
And is there a way to overlay any element on the website (even flash)?

Upvotes: 0

Views: 200

Answers (1)

nmaier
nmaier

Reputation: 33192

You should use contentScriptFile.

And then you should use DOM APIs that don't suck performance and "shoot yourself in the foot"-wise (that are not .innerHTML), something like:

var div = document.createElement("div");
div.style.backgroundColor = "rgba(0,0,0,0.5)";
...
var input = document.createElement("input");
input.setAttribute("type", "button");
...
div.appendChild(input);
document.body.appendChild(div);

MDN has the documentation.

As for styles: This one is tougher. Usually people will not inject DOM nodes into the page itself (not just because of CSS compatibility, but to avoid conflicts in Javascript and/or the DOM), but instead create an <iframe> which then has it's own set of CSS rules and own Javascript environment and is even subject to the same origin policy, which will hinder the website to mess with the contents, if done right.

Upvotes: 1

Related Questions