Glue Interactive

Using jQuery Inside Your Firefox Extension

This post dropped Oct 30th 2008, 22:25, in to Web Development

For a project at work we've been building a Firefox extension. It's slow, tedious work, with lots of time spent in the breakpointer functionality of Venkman. Thankfully Firefox extensions are basically javascript, and as I heard rumors of, you can embed jQuery inside of one.

How? Well it's quite simple. In your overlay.xul file, just include it like you would any other js file.

<script type="application/x-javascript" src="chrome://extensionname/content/jquery-1.2.6.min.js" />

Yup, that's it! Now you have access to all the usual jQuery functionality like element.click(), element.attr() and even the $.ajax calls, all within the scope of your extension. Thus, you can write extension code like this:

$('.toggle').attr('disabled', true);

Where it will select all XUL elements in your extension with the class toggle and set the disabled attribute to true.

If you want to have access to the browser DOM, you can access it via the document.defaultView attriute globally.  Most times the defaultView variable is available inside of the event object if you've bound to one. Then, in order to effect the browser DOM, all you have to do is make use of the (often ignored) 2nd parameter of the $ function, the conext you'd like jQuery to work in.

In our case it's the browser's DOM.  For example, to highlight all links on the page that are rel=nofollow, you just have to do this:

doc = document.defaultView;
jQuery("a[rel='nofollow']", doc).css({border: 'dotted 1px red', backgroundColor: 'pink'});

Now you have the power!

Post Details

Published
Oct 30th 2008, 22:25
Category
Web Development
Author
Jeff