File Under: Browsers, JavaScript

Get Started With Greasemonkey

Greasemonkey is a Firefox extension that gives you tremendous control over how a page appears in your browser. If you can imagine JavaScript that you wish would run when a site loads, you can make it so. Rearrange a site’s layout, hide annoying elements (ads?), or replace every occurrence of “David Lee Roth” with “Sammy Hagar.” All it takes is a few lines of JavaScript and the Greasemonkey extension.


Contents

  1. What You Need
  2. Install the Greasemonkey Extension
  3. Install a Greasemonkey Script
  4. Disecting the Hello World Greasemonkey Script
  5. Getting More Advanced: Hiding Elements
  6. Example Project: Create a Floating Menu from Headings
    1. Floating Menu Code
    2. What’s it Doing?
  7. Where To Go From Here

What You Need

  • Firefox web browser
  • Greasemonkey extension for Firefox
  • Intermediate knowledge of JavaScript

Install the Greasemonkey Extension

Within Firefox, go to the Greasemonkey extension page and click “Add to Firefox.” Follow the instructions, then restart Firefox.

Image:Greasemonkey-install.png

Once Greasemonkey is installed, you should see it in the bottom right of the status bar. If the monkey is faded and frowning, give it a click to activate Greasemonkey.

Image:Greasemonkey-offon.png

Nothing happened, right? That’s because Greasemonkey only reacts when there is a script set for the site you’re visiting. To see which scripts are enabled and for which sites, right-click the monkey and choose “Manage user scripts.”

Image:Greasemonkey-settings.png

Here, I have a script installed for any URL on the sub-domain images.google.com. You can edit scripts (and the URLs for which it runs) and add new scripts from this settings page.

In the next section, you’ll add a script to Greasemonkey to see how it works before writing your own.

Install a Greasemonkey Script

You can find all sorts of Greasemonkey scripts at userscripts.org. In order to find something good, you’ll likely need to make heavy use of the search function.

To keep things simple, try installing this Hello World script we cooked up.

Greasemonkey should prompt you regarding the script installation. If you are instead see the actual JavaScript code, you likely don’t have Greasemonkey installed, or haven’t restarted. A recognized Greasemonkey script contains a filename ending in .user.js. So, whenever Greasemonkey sees a file that matches that format, it prompts you to install the script.

In addition to this direct method of installation, you can add scripts that are stored on your computer via the Manage User Scripts window mentioned in the previous section.

Now that you have the example script, helloworld.user.js, installed, let’s check it out. Go to any web page. Heck, even reload this one. You should see a message that reads: Monkey sez… “Hello World!”

Image:Greasemonkey-helloworld.png

In the next section I’ll go into the structure of this simple example script. In the meantime, you may prefer to go into Manage User Scripts and disable this script, or it might become mighty annoying.

Disecting the Hello World Greasemonkey Script

In the previous section you installed a Greasemonkey script that creates a JavaScript alert message every time a page loads. Not very useful, you say? You’re right, though as an example it shows just how easy Greasemonkey is to write if you already know some JavaScript.

Here is the full source code of helloworld.user.js:

// ==UserScript==

// @name          Webmonkey's Hello World

// @namespace     http://www.webmonkey.com

// @description   A basic example of Greasemonkey that causes an alert at each page load.

// @include       *

// ==/UserScript==



alert('Monkey sez... "Hello World!"');

Most of the code above is metadata, which doesn’t even need to be included to work. The name, description, etc., are used by Greasemonkey to reference each script in the Manage User Scripts screen. The metadata is also used on sites like userscripts.org to show information about the scripts. Check out available metadata properties.

With the metadata out of the way, that leaves just one line, which looks exactly like normal JavaScript. The alert function tells the browser to give the message passed to it in a string value.

Remember, Greasemonkey scripts are JavaScript. It’s as if you can go into a site’s code and insert what you wish was there.

So, the absolute most basic script example would be only this one line:

alert('Monkey sez... "Hello World!"');

As I mentioned before, that’s not very useful, except as an example. In the next section, we’ll do something a little more advanced.

Getting More Advanced: Hiding Elements

This next example should provide a glimpse into the power of Greasemonkey, even if it isn’t super useful on its own. The script in this section finds every image on the page (created with the <img> tag) and hides it.

You can install the script with the link below, or better yet, create your own file and try it yourself.

Here’s the code for hidingelements.user.js:

// ==UserScript==

// @name          Webmonkey's Hiding Elements

// @namespace     http://www.webmonkey.com

// @description   An example Greasemonkey script that hides every image.

// @include       *

// ==/UserScript==



var imgs = document.getElementsByTagName('img');

for (i=0; i<imgs.length; i++)

{

  imgs[i].style.visibility = 'hidden';

}

Again, it starts with metadata. Then, it grabs all the elements with the tag “img” and saves them to a variable. Next, the for loop goes through each image one by one and sets the visibility CSS value to “hidden”.

Save your file and then load it in Firefox to install into Greasemonkey. Now visit a page with images and they won’t be there. Through the magic of Greasemonkey, you’ve changed the way you’re viewing the web.

In the final example, I’ll show how you can create your own menu for a page.

Example Project: Create a Floating Menu from Headings

Here’s the scene: You’re viewing a large page with lots of content. Like this tutorial page, it’s separated into sections quite nicely, but once you’re down the page there is no menu to other content.

Enter our example project: a menu to page sections that floats as you scroll the page. This script may be useful for many sites, but I’m specifically thinking about those based on MediaWiki, like Webmonkey and Wikipedia.

As with other examples, you can install it directly or use the code below.

Try running the script on our JavaScript Events page, for example. Here’s what you’ll see when the floating menu code works:

[Image:Greasemonkey-floatingmenu.png]


Floating Menu Code

Let’s get some grease in this monkey. Here’s the code for the floating menu. It’s a little longer than the others, because it has more to do:

// ==UserScript==

// @name          Webmonkey's Floating Menu

// @namespace     http://www.webmonkey.com

// @description   A Greasemonkey script that finds h2 tags and creates a floating menu of them.

// @include       *

// ==/UserScript==



var headers = document.getElementsByTagName('h2');

var menu = '';

for (i=0; i<headers.length; i++)

{

  // Determine menu text

  var thismenu = headers[i].innerHTML;

  thismenu = thismenu.replace(/<[^>]*>/g, ''); // Remove HTML tags

  thismenu = thismenu.replace(/[[^]]*]/g, ''); // Remove anything within square brackets



  // Create menu item

  var thisid = headers[i].id;

  if (thisid == '')

  {

    thisid = 'h2header' + i;

    headers[i].id = thisid;

  }

  menu += '<li><a href="#' + thisid + '"">' + thismenu + '</a></li>';

}



// Create menu

if (menu != '')

{

  menuobj = document.createElement('ul');

  menuobj.style.position = 'fixed';

  menuobj.style.top = '10px';

  menuobj.style.left = '10px';

  menuobj.style.padding = '20px';

  menuobj.style.backgroundColor = '#fff';

  menuobj.innerHTML = menu;

  body = document.getElementsByTagName('body')[0];

  body.appendChild(menuobj);

}



What’s it Doing?

After the metadata, we use getElementsByTagName to grab all the <h2> tags. This might look familiar from the previous version where we grabbed all the images. I chose h2 because it is often used as section titles (h1 is reserved for titles).

Let’s look at the rest in a couple pieces.

var menu = '';

for (i=0; i<headers.length; i++)

{

  // Determine menu text

  var thismenu = headers[i].innerHTML;

  thismenu = thismenu.replace(/<[^>]*>/g, ''); // Remove HTML tags

  thismenu = thismenu.replace(/[[^]]*]/g, ''); // Remove anything within square brackets



  // Create menu item

  var thisid = headers[i].id;

  if (thisid == '')

  {

    thisid = 'h2header' + i;

    headers[i].id = thisid;

  }

  menu += '<li><a href="#' + thisid + '"">' + thismenu + '</a></li>';

}



The script goes through the h2 tags one at a time. For each one, if finds the text inside it, looks for an id (and may create one), and adds a new list item with a link to this section. The menu variable is holding the HTML that will eventually make up the floating menu.

Because MediaWiki puts several tags within the h2 tag, I remove HTML to have only the text remaining. Well, there’s also a little [edit] link, so I zap it, too. I used regular expressions to do the replacing, which might look confusing if you’ve never seen them. Webmonkey has a whole regular expressions tutorial for the uninitiated.

After we’ve seen each h2 tag, we need to create the actual menu. Here’s that final block of code:

// Create menu

if (menu != '')

{

  menuobj = document.createElement('ul');

  menuobj.style.position = 'fixed';

  menuobj.style.top = '10px';

  menuobj.style.left = '10px';

  menuobj.style.padding = '20px';

  menuobj.style.backgroundColor = '#fff';

  menuobj.innerHTML = menu;

  body = document.getElementsByTagName('body')[0];

  body.appendChild(menuobj);

}

The first line creates the actual menu object, an unordered list, that will get added to the page.

Most of this code is the CSS styles necessary to be fixed into the upper left corner of the screen. Every line with .style is taking the place of CSS that would normally go into a stylesheet. Greasemonkey can’t alter the site’s stylesheet directly.

Finally, the object, now fully styled, is added to the page.

You’ve now created a functional Greasemonkey script that does something that might even be useful. Hopefully you see there’s some power here waiting to be harnessed.

Where To Go From Here

You know that power of Greasemonkey I’ve been talking so much about? Now’s the time when you can go forth and use it.

If you need some inspiration, you can usually find it at userscripts.org. For example, check out everything people have written to alter GMail.

Now that you know what can be done with Greasemonkey, the best ideas will come to you at sites you visit often. Is there something that you wish worked better? Chances are you can figure out how to make it happen with Greasemonkey.