Become a Greasemonkey Ninja with jQuery

Programming Tips

This is for all the Greasemonkeyers in the house who want to learn how to be much more productive when it comes to hacking together Greasemonkey script by using my favorite Javascript library: jQuery. jQuery will turn a 700 line Greasemonkey script into a 12 line Greasemonkey script. I learned about jQuery through all of the Greasemonkey scripts I created to work with Friend Feed.

This is advanced stuff that is of interest to people writing Javascript. If you’re just a Greasemonkey user then you can safely skip this one.

What is jQuery?

jQuery lets you very concisely access any element on the page through the use of normal CSS selectors and custom selectors specific to jQuery. If you can access it with CSS or XPath then you can access it with jQuery. It gives you more options for selecting elements than CSS or XPath.

It also support method chaining which makes for some stupidly concise javascript code compared to the normal pain of walking the DOM or calling XPath that you see in most Greasemonkey scripts.


    function ff_show_domains() {
        $("a.main").each(function() {
            var uri = $(this).attr('href').replace('www.','').split('/');
            var domain = uri[2];
            …

        });
    }

The other thing I love about jQuery is that it has plugins you can grab and import into your Greasemonkey scripts. Check out this concise plugin that lets you call Firebug’s console.log from within a jQuery method chain. That’s a perfect example of how powerful jQuery is.

jQuery Makes Me Happy

The hardest part of using jQuery with Greasemonkey is importing it. There are several ways to include jQuery into a Greasemonkey script. I’m going to walk through three of them. I would love it if jQuery became an official component of Greasemonkey, and I think that would greatly increase the number of useful Greasemonkey scripts being created.

Technique #1: Site already uses jQuery

If the site already uses jQuery (friendfeed.com, wordpress admin) then you’re in luck: you don’t have to import it.


$ = unsafeWindow.jQuery;
console.log( $('p') );

You can find out if the site uses jQuery by running ‘alert($)‘ in the Firebug console or by looking at the imported scripts.

Technique #2: Import from Remote Host

If the site doesn’t already use jQuery (boo, hiss) then you can import jQuery from jquery.com.

Joen Piedra has example code and a script showing how to do this.


// Example from http://www.joanpiedra.com/jquery/greasemonkey/

// Add jQuery
    var GM_JQ = document.createElement('script');
    GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
    GM_JQ.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(GM_JQ);

// Check if jQuery's loaded
    function GM_wait() {
        if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }
    else { $ = unsafeWindow.jQuery; letsJQuery(); }
    }
    GM_wait();

// All your GM code must be inside this function
    function letsJQuery() {
        alert($); // check if the dollar (jquery) function works
    }

It’s a similar technique to the jQuerify bookmarklet that lets you add jQuery to any site in one click so that you can play around in the Firebug console.

Technique #3: Embed in Your Script

This is my preferred method because it reduces the number of external dependencies of your script. You can put all of the code for jQuery directly into your script so the user only has to download it once. This will reduce the load time of the page you’re Greasemonkeying since it is always faster to load local files than to load a Javascript library over the internet.

  1. Copy the packed version of jQuery into your script

  2. Use jQuery :)

Here’s an example of one of my scripts where I use the embedded packed jQuery as well as an embedded image file. That script runs on Soundamus (a very cool site if you’re a Last.FM listener, check it out) and adds links to search for the artist/album on an different site.

Here is the active javascript code that uses jQuery to do all the magic.


$('.post').each(function(i) {
		  var artist = $(this).find('a:eq(0)').text();
		  var album = $(this).find('a:eq(1)').text();
		  var search_link = SEARCH_URL+encodeURI(artist+" "+album);
		  $(this).prepend('<div style="clear:both; float:right;"><a title="Search for '+artist+' - '+album+'" href="'+search_link+'"><img src="'+data+'" /></a></div>');
		  $(this).css('clear','both');

});

Actually Related Posts

3 Comments

  1. Posted May 08, 2008 at | Permalink

    I find it much easier to check if a site is using jquery by running alert($); in the firebug console, you don’t have to sort through all of their included files that way.

    I also use firebug console as my quick and dirty greasemonkey replacement.

  2. Posted May 08, 2008 at | Permalink

    Here’s a plugin I should have included, makes it easy to use Firebug profile with jQuery:
    http://osteele.com/archives/2008/05/jquery-profile-plugin

    http://devkick.com/blog/useful-jquery-a-compilation-of-jquery-utilities/

    http://noteslog.com/chili/

  3. Ryan
    Posted May 09, 2008 at | Permalink

    You can find a bunch of nice jquery tuts and examples here: http://www.noupe.com/tutorial/51-best-of-jquery-tutorials-and-examples.html

One Trackback

  1. [...] // Internet Duct Tape blogging / programming / technology / lifehacks Skip to content Subscription OptionsMost Popular PostsIDT Labs - Free Software ToolsWordPress.com Resources - Tips, Tricks and ToolsWordPress.com Theme ReviewsWordPress.com Theme Review HelpGreasemonkey script: WordPress Category ResizerWordPress.com 7 Day Referrer ParserPerl Script - WordPress.com 7 Day Referrer ParserGreasemonkey Script: Akismet Auntie Spam for WordPressGreasemonkey Script: Find images that are too wideTag Cloud Generator for WordPress.comTag Cloud Generator AdvancedTag Cloud Generator - Release NotesWordPress Themes by InternetDuctTape.comBlack and Blue and Read All Over Theme for WordPress SandboxMoon Under Uranus Theme for WordPress SandboxMiscellanious WordPress Scripts and ToolsGreaseMonkey Script: WordPress Comment NinjaTechnorati Favorite Your FansTechnorati Favorite Your Fans - Release NotesGreasemonkey script: Flickr always search for Creative Commons licensed photosGreasemonkey Script: Yahoo Pipe CleanerTag CloudAll Posts by Category and TitleSeriesGift Guide for GeeksWelcome to Internet Duct Tapegoogle1ec000b3808eedbf.htmlAbout MeDisclosureImage Credits « Become a Greasemonkey Ninja with jQuery [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*