ManticMoo.COM All Articles Jeff's Articles
Jeffrey P. Bigham

Arbitrary Javascript in a Web Page using a Firefox Extension

Jeffrey P. Bigham

Related Ads

The GreaseMonkey Firefox extension allows users to insert arbitrary Javascript code into web pages to alter them as they see fit. It's an incredibly handy extension. In this short article, I display a short piece of Javascript code that simulates much of this functionality because sometimes you don't need all of the power of GreaseMonkey, you just want to be able to muck around with a web page on-the-fly with Javascript.

Reasonably experienced Javascript developers will know how to change the contents of a web page once they have access to the HTML document that they want to change, but this isn't straightforward to get. The Javascript code in the extension will exist on the XUL file that it's included in and getting from that to the browser's window, isn't exactly straightforward. Here's one way to do it that works pretty well:


// First get the browser object.
var gb = window.gBrowser;

// Now the window.
var active_window =
gb.getBrowserAtIndex(gb.mTabContainer.selectedIndex).contentWindow;

// Finally, the document.
var active_document = active_window.document;

// Get a reference to the body tag.
var body_tags = active_document.getElementsByTagName("body");

// Fail in this simple example if there's no body tag.
if(body_tags.length <= 0) {
  return;
}

// Should only be one body tag,
// but choose the first regardless.
var body_tag = body_tags.item(0);

// Create the node to be added.
// In this case, 

My text string

var node_to_insert = active_document.createElement("p"); node_to_insert.innerHTML = "My text string"; // Finally, add it into the body tag as a new child. body_tag.appendChild(node_to_insert);

That's all there is to it, however, for code that gets released in the wild, security is a huge concern because of the difference in protection models between the trusted Javascript code in an extension and the untrusted Javascript found in the wild. For more on this, see my companion article:
Inserting Javascript in an Adversarial World.

Jeffrey P. Bigham
ManticMoo.COM All Articles Jeff's Articles