- BetterExplained - https://betterexplained.com -

How To Make a Bookmarklet For Your Web Application

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

Here’s a few bookmarklets I use regularly:

How easy is it?

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

How To Make a Bookmarklet For Your Web Application

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:

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:

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:

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:

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:

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://static.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.

Have fun.

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