Browser buttons (bookmarklets) are shortcuts that act like a simple browser plugin. Their advantages include:

  • Fast installation: Just add a link to your bookmarks
  • Convenient: Use features while on your current page
  • Easy to write: Bookmarklets are just like making a webpage; there’s no need to write a whole browser plugin
  • Cross-browser: The same bookmarklet can work in IE, Firefox, Opera and Safari.

Here’s a few bookmarklets I use regularly:

How easy is it?

Only one way to find out. Try the instacalc bookmarklet right here:

  • Click this link: instacalc bookmarklet.
  • A calculator opens in the corner of the page. Type 1 + 1 to see the result.
  • Select this text 15 mph in fps and click the link again. Voila! The text is automatically inserted.
  • Close the window by clicking the red “x”

Neat, eh? No install, just click and go. To save the bookmarklet, right click the link and “add to favorites/bookmarks”. Now you can open the calculator on any page.

Today we’ll walk through the anatomy of a bookmarklet, dissect a few, and give you the tools to build your own.

Bookmarklets 101

Regular bookmarks (aka favorites) are just locations to visit, like “http://gmail.com”. Bookmarklets are javascript code that the browser runs on the current page, and they’re marked by “javascript:” instead of “http://”.

When clicking a bookmarklet, imagine the page author wrote <script>bookmarklet code here</script> — it can do almost anything. There are a few restrictions:

  • Restricted length: Most URLs have a limit around 2000 characters, which limits the amount of code you can run. There’s a way around this.
  • No spaces allowed: Some browsers choke on spaces in a URL, so yourcodelookslikethis. We have a trick for this too.

A simple bookmarklet looks like this:

<a href="javascript:alert('hi');">my link</a>

Click this link to see it in action. This example isn’t too wild, but the key is that bookmarklets let you run code on an existing page.

What do you want to do?

Your bookmarklet should do something useful. Ideas include:

  • Transform the current page. Do find/replace, highlight certain words or images, change CSS styles…
  • Open/overlay a new page. Open a new page or draw a window on the current one, like a sidebar
  • Send data to another site. Post, share, or upload the current URL or selected text (like Google translate).
  • Look at the bookmarklet directories for more inspiration.

People spend most of their time on other sites. Web application authors, think creatively: how can people use your service when away from your site?

Javascript for Bookmarklets

A bookmarklet can use any javascript command, but certain ones are helpful:

Get current page title: document.title Get the current URL: location.href Get the currently selected text:

  // get the currently selected text
  var t;
  try {
    t= ((window.getSelection && window.getSelection()) ||
(document.getSelection && document.getSelection()) ||
(document.selection &&
document.selection.createRange &&
document.selection.createRange().text));
  }
  catch(e){ // access denied on https sites
    t = "";
  }

Make text url-safe: encodeURIComponent(text) (and corresponding decodeURIComponent()). The page title or URL may have invalid characters (spaces, slashes, etc.) so it’s a good habit to encode them before sending them over (spaces become %20, etc.).

Dissecting the Delicious Bookmarklet

Here’s the code for the delicious bookmarklet (spaces added for readability):

javascript:location.href='http://del.icio.us/post?v=4;
url='+encodeURIComponent(location.href)+';
title='+encodeURIComponent(document.title)

And here’s what’s happening:

  • Change to a new URL (to post the item)
  • Specify query parameters for the current document’s url (location.href) and title (document.title)
  • Make the paramaters url-safe with encodeURIComponent

Once you tag and save the post, delicious sends you to the original page. How do they know where? Because it was sent along in the original request!

Bookmarklet Interface Ideas

Imagine this: Your users are browsing for cat photos (or the journals of the American Chemical Society, but probably lolcats) when they click your killer Web 2.0 bookmarklet. What happens?

Bookmarklet interface ideas

Common techniques are:

  • Take the user to a new page. Hopefully, you can use some data from the current page, otherwise it’s a regular bookmark.
  • Frame the current page, like Google translate or Stumbleupon. This is similar to the first technique, but your site displays the old page inside the window.
  • Overlay a new interface. Use CSS absolute positioning to make a window in a set place, or fixed positioning to have the window follow you as you scroll. Beware the CSS bugs.

Overlaid windows are great, but won’t that be hard to cram into a single line?

The Big Trick: Dynamic Javascript

Direct javascript works fine if you just want to redirect the user to another page, like the delicious bookmarklet. The no spaces, 2000 character limit really hurts when you want a more complicated interface.

There’s a fix: Our bookmarklet becomes a stub to load another (regular) javascript file. Here’s the code (spaces added for readability):

javascript:(function(){
  _my_script=document.createElement('SCRIPT');
  _my_script.type='text/javascript';
  _my_script.src='http://mysite.com/script.js?';
  document.getElementsByTagName('head')[0].appendChild(_my_script);
})();

Here’s how it works:

  • Define an anonymous function to download the script
  • Create a script element, type text/javascript. We can’t use var _my_script because of the spaces, so choose a unique name.
  • Set the src of the script to our real javascript file. This file could pull down more javascript also.
  • Add the script element to the current page

And that’s it! Our bookmarklet can now load any javascript we please, without the annoying restrictions. An added bonus: see how many people are using your tool, and you we can change our script (fix bugs or add features) on the server.

Dissecting the Instacalc Bookmarklet

Here’s the steps I went through to make the instacalc bookmarklet

Create a bookmarklet interface

I made a trimmed-down page designed for the bookmarklet. If you click the page it appears fullscreen, but it resizes to the parent container. I planned on hosting this page inside a smaller iframe.

Create a stub bookmarklet

Because I wanted to get the currently selected text and overlay an interface, I knew I couldn’t fit my javascript into 2000 characters. So I used the dynamic javascript technique above to get the real javascript file.

Careful caching

I didn’t want to cache the bookmarklet javascript in case I wanted to change its behavior (but I did cache the other files). I added a dummy query parameter using Math.random(), which forces the browser to download the file each time. Since the script is small, this wasn’t too much of an issue.

instacalc_script.src='http://instacalc.com/gadget/instacalc.bookmarklet.js?x='+(Math.random());

Build the interface

The script to build the interface is pretty straightforward. There’s some helper functions for encoding (instacalc stores data using base64). The script gets the selected text, constructs the URL for the iframe, and loads it up. It generates the CSS to have a fixed window on the top right of the screen, and a button to hide the window.

As a slight trick, if the bookmarklet is run again on the same page, it just shows the existing window instead of creating a new iframe.

Tips & Tricks

Keep this in mind when making your bookmarklet:

Make it friendly. Don’t interrupt the user’s flow. Bring up the window on the same page, or a new page that closes. If you must redirect the user to their original page.

This is important: the user was nice enough to use your service, so put ‘em back where they were!

Make it fast. After you’ve got it working, tweak your bookmarklet’s speed using the following techniques

Give people instructions. Bookmarklets aren’t that common, so help people understand your tool. A few instructions (“right click this link and add to bookmarks/favorites”) and a screenshot go a long way.

The gotcha: cross-domain communication

Because of cross-domain security restrictions, your bookmarklets can’t use fancy-pants Ajax techniques to communicate with your site. The easiest way to communicate is through query parameters in a URL.

Debugging

What’s programming without bugs? Use firefox to debug your javascript and CSS. Instead of clicking a bookmarklet each time, just make a page that runs the javascript file directly: <script src="...">. This is what the bookmarklet does.

Once the dummy page is working, try your bookmarklet on other sites. You’d be surprised how other CSS rules can mess up your carefully positioned elements (remember, you’re running in the context of another site).

Links & Resources

I’m sure you’ll come up with crazy ways to use your newfound toy. The main benefits are simple installation, compatibility, and being able to interact with the current page.

  • There are crunching tools to make your javascript bookmarklet-friendly. But it’s nice to just dynamically load the real script and be done with it.

  • People have put the delicious bookmarklet on steroids, such as letting you type the tags in the url before hitting the button.

  • Taking this to the extreme, Greasemonkey is a firefox plugin letting you run really powerful scripts. For example, there was a script to add a “delete” button to Gmail before it was available.

Have fun.

{{ strings.title }}

{{item.title}}
{{item.text }}
Show {{ filteredItems.length - limit }} more

Other Posts In This Series

  1. Starting Ruby on Rails: What I Wish I Knew
  2. Intermediate Rails: Understanding Models, Views and Controllers
  3. A Simple, Comprehensive Overview of Javascript
  4. Using JSON to Exchange Data
  5. How To Make a Bookmarklet For Your Web Application