O'Reilly Network    
 Published on O'Reilly Network (http://www.oreillynet.com/)
 See this if you're having trouble printing code examples


What Is Greasemonkey

by Mark Pilgrim, author of Greasemonkey Hacks
09/01/2005
Greasemonkey
Greasemonkey is a Firefox extension that allows you to write scripts that alter the web pages you visit. You can use it to make a website more readable or more usable. You can fix bugs that the site owner can't be bothered to fix themselves. You can alter pages so they work better with assistive technologies that speak to a web page aloud or convert it to Braille. You can even automatically retrieve data from other sites to make two sites more interconnected.

In This Article:

  1. Getting Started
  2. The Anatomy of a User Script
  3. Coding a User Script
  4. Managing User Scripts
  5. Finding User Scripts

By itself, Greasemonkey does none of these things. In fact, after you install it, you won't notice any change at all, until you start installing what are called "user scripts." A user script is just a chunk of JavaScript, the same scripting language you use on your own website. But user scripts don't run on your own website; they can run on any website, and they can do anything JavaScript can do. In fact, they can do more than that, because Greasemonkey provides special API functions that give user scripts even more power than traditional JavaScript.

Greasemonkey has existed for less than a year, and hundreds of people have already written thousands of Greasemonkey scripts to scratch their own personal itches. Web enthusiasts with zero JavaScript experience have written scripts to route around broken websites, alter site styles, and "roll back" ill-conceived site redesigns. More experienced coders have created link trackers, password managers, and personal shopping agents. Some have even added entirely new features to complex web applications--without ever needing to talk to the application developers or wait for bureaucratic approval.

Clearly, there were a lot of itches waiting to be scratched.

Getting Started

The first thing you need to do to get started with Greasemonkey is install it. Open Firefox and go to greasemonkey.mozdev.org. Click the Install Greasemonkey link. (At time of writing, the latest version is 0.5.1.) Firefox may not let you install it, since it maintains a whitelist of websites that are allowed to install software on your machine. (See Figure 1.)

figure 1
Figure 1: Extension whitelist

Type the address sand click "Allow" to allow this site, then click the "Install Greasemonkey" link again. This time, Firefox will pop up the Install dialog to confirm that you really want to install it. After Greasemonkey downloads, quit Firefox and relaunch it to finish the installation.

As I said, Greasemonkey doesn't do anything by itself, except add a few items to the Tools menu and the right-click context menu. All Greasemonkey does is enable you to install "user scripts" that customize specific web pages.


Greasemonkey Hacks

Related Reading

Greasemonkey Hacks
Tips & Tools for Remixing the Web with Firefox


The first user script I ever wrote was called Butler. It adds functionality to Google search results. To see a brief description of the functionality that Butler offers, visit the Butler home page. To install it, right-click (Control-click on a Mac) the link titled "Download version 0.3." From the context menu, select "Install User Script...."

Greasemonkey pops up a dialog titled "Install User Script," displaying the name of the script you are about to install (Butler), a brief description of what the script does, and a list of included and excluded pages. All of this information is taken from the script itself, as we'll see in a moment. (See Figure 2.)

figure 2
Figure 2: Install user script

Click OK to install the Butler user script. If all went well, Greasemonkey displays the following alert: "Success! Refresh page to see changes."

Now, search for something in Google. In the search results page, there is a line at the top of the results that says "Try your search on Yahoo, Ask Jeeves, AlltheWeb, ...," [figure 3]. There is also a banner along the top that says "Enhanced by Butler." All of these options were added by the Butler user script. (See Figure 3.)

figure 3
Figure 3: Butler-enhanced search results

In addition to web search results, Butler also alters image search results by adding links to a variety of image search engines (See Figure 4). It even adds links in Froogle to other product comparison and shopping sites. (See Figure 5.)

figure 4
Figure 4: Butler-enhanced image search results

figure 5
Figure 5: Butler-enhanced product search results

The Anatomy of a User Script

Hopefully I've piqued your interest. But how does this all work? It's surprisingly simple. Let's crack open the Butler user script and see how it works.

Every user script has a section of metadata, which tells Greasemonkey about the script itself, where it came from, and when to run it. You can use this to provide users with information about your script, such as its name and a brief description of what it does. You can also provide a default configuration for where the script should run: one page, one site, or a selection of multiple sites.

The metadata section of the Butler user script looks like this:

// ==UserScript==
// @name        Butler
// @namespace   http://diveintomark.org/projects/butler/
// @description Link to competitors from Google search results
// @include     http://*.google.*/*
// ==/UserScript==

There are five separate pieces of metadata here, wrapped in a set of Greasemonkey-specific comments. Let's take them in order, starting with the wrapper:

Wrapper

// ==UserScript==
//
// ==/UserScript==

These comments are significant and must match this pattern exactly. Greasemonkey uses them to signal the start and end of a user script's metadata section. This section can be defined anywhere in your script, but it's usually near the top.

You can specify the items of your user script metadata in any order. I like @name, @namespace, @description, @include, and finally @exclude, but there is nothing special about this order.

Name

// @name        Butler

This is the name of your user script. It is displayed in the install dialog when you first install the script and later in the Manage User Scripts dialog. It should be short and to the point.

@name is optional. If present, it can appear only once. If not present, the default is the filename of the user script, minus the .user.js extension.

Namespace

// @namespace   http://diveintomark.org/projects/butler/

This is a URL, which Greasemonkey uses to distinguish user scripts that have the same name but are written by different authors. If you have a domain name, you can use it (or a subdirectory) as your namespace.

@namespace is optional. If present, it can appear only once. If not present, the default is the domain from which the user downloaded the user script.

Description

// @description Link to competitors from Google search results

This is a human-readable description of what the user script does. It is displayed in the install dialog when you first install the script and later in the Manage User Scripts dialog. It should be no longer than two sentences.

@description is optional. If present, it can appear only once. If not present, the default is an empty string.

Though @description is not mandatory, don't forget to include it. Even if you are writing user scripts only for yourself, you will eventually end up with dozens of them, and administering them all in the Manage User Scripts dialog will be much more difficult without descriptions.

Include

The @include directive lists the URLs and wildcards that tell Greasemonkey where to run this user script:

// @include     http://*.google.*/*

There is also an @exclude directive, which shares the same syntax. The @include and @exclude directive can each be a URL; a URL with the * character as a simple wildcard for part of the domain name or path; or simply the * wildcard character by itself. In this case, we are telling Greasemonkey to execute the Butler script on all Google sites in all countries, all subdomains (such as http://froogle.google.com/), and on all pages within any of those Google properties. Everywhere Google is, we want to be there.

@include and @exclude are optional. You can specify as many included and excluded URLs as you like, but you must specify each on its own line. If neither is specified, Greasemonkey will execute your user script on all sites (as if you had specified @include *).

Coding a User Script

User scripts are written in JavaScript. On every page you visit, Greasemonkey looks through the list of installed user scripts, determines which ones apply to this page (based on the @include and @exclude directives), and executes them after the page is loaded but before it is rendered. The scripts themselves can do anything you like. Butler works on a number of different Google pages, and does different things to each type of page, so it contains some code to check where exactly we are and calls the appropriate methods.

For example, on Google web search results pages, Butler adds the "Enhanced by Butler" banner along the top, removes the ads along the top and right sides of the results, adds the "try your search on..." line, and may also add other "try your search on..." lines for inline movie reviews, news headlines, weather forecasts, and product results. The code to do this is straightforward:

var href = window.location.href;

// Google web search
if (href.match(/^http:\/\/www\.google\.[\w\.]+\/search/i)) {
  Butler.addLogo();
  Butler.removeSponsoredLinks();
  Butler.addOtherWebSearches();
  Butler.addOtherInlineMovieReviews();
  Butler.addOtherInlineNewsResults();
  Butler.addOtherInlineForecasts();
  Butler.addOtherInlineProductSearches();
}

Each of these functions is defined elsewhere in the Butler user script. (Greasemonkey user scripts are always self-contained. If you need to bundle multiple interdependent scripts, you're probably better off writing a browser extension.)

Managing User Scripts

The Butler user script barely scratches the surface of what Greasemonkey can do. There are literally thousands of user scripts, some targeting a single page or a single site, others that work on every page. Because you can have multiple user scripts installed, Greasemonkey provides a graphical interface for managing them.

From the Firefox Tools menu, select "Manage User Scripts" (See Figure 6). Here you can see all the user scripts you have installed, change their configuration, disable them temporarily, or uninstall them completely. You can even edit a user script "live" and see your changes immediately, without restarting Firefox. This is enormously helpful while you're developing your own user scripts.

figure 6
Figure 6: Manage User Scripts

Finding User Scripts

Many user scripts are available at the Greasemonkey script repository. Here are some of my favorites:

Have fun remixing the web!

Mark Pilgrim is an accessibility architect who can be found stirring up trouble at diveintomark.org.


Return to the O'Reilly Network

Copyright © 2009 O'Reilly Media, Inc.