How To Make a Bookmarklet For Your Web Application

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.
  • 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.




Tools of the trade:


22 Comments »

Trackbacks & Pingbacks

  1. Pingback by سردال » ملخص الأسبوع الماضي — April 17, 2008 @ 10:41 am

  2. Pingback by Retazos de la web del 2008-04-17 (microblogging) | hombrelobo, una mente dispersa — April 17, 2008 @ 4:43 pm

  3. Pingback by » How To Make a Bookmarklet For Your Web Application notyournews — April 17, 2008 @ 4:59 pm

  4. Pingback by links for 2008-04-18 « Bloggitation — April 17, 2008 @ 5:34 pm

  5. Pingback by Cronaca di un’avventura formativa » links for 2008-04-19 — April 19, 2008 @ 1:38 am

  6. Pingback by The Bastard’s Kitchen » Home Page — April 24, 2008 @ 12:24 pm


Comments

  1. Very well explained, nice post!

    machinehuman — April 16, 2008 @ 7:24 pm

  2. Thanks again for another useful post.

    Tiago — April 16, 2008 @ 9:23 pm

  3. it will help me a lot

    bharatboom — April 16, 2008 @ 9:24 pm

  4. Thanks guys, glad you’re finding it useful.

    Kalid — April 16, 2008 @ 10:36 pm

  5. Very useful tips….thanks


    http://www.redesignyourbiz.com
    Visit our website for your webdesigning needs and also download amazing wallpapers or send ecards.

    Designer — April 17, 2008 @ 12:54 am

  6. Really useful, we were planning to use bookmarklets to increase the use of our web startup. So that user need not come to our site to get the work done. I had a vague idea how to do this one, but your post explains a great deal about the nitty gritties. thanks a ton.

    Chandoo — April 17, 2008 @ 4:38 am

  7. Very useful! thanks alot!

    BeyondRandom — April 17, 2008 @ 5:49 am

  8. @Designer, Chandoo, BeyondRandom: You’re welcome! :)

    Kalid — April 17, 2008 @ 10:59 am

  9. You say “We can’t use var _my_script because of the spaces” but you can use “%20″ in place of a space in javascript URLs. Actually, looking at my “Google Bookmark” bookmarklet they use “var a=…” with a normal space.

    Aaron — April 19, 2008 @ 8:19 am

  10. Hi Aaron, good point — some browsers allow use of %20 in place of spaces, and some support spaces directly. In general I find it easier to avoid spaces altogether.

    Kalid — April 20, 2008 @ 10:40 pm

  11. Hi, I was wondering where can I host a js file to load dinamically. I don’t really want to host it on my site, is there some >>long term

    Brian — April 23, 2008 @ 11:13 am

  12. ..some long term solution for this?

    Brian — April 23, 2008 @ 11:42 am

  13. Hi Brian, I would take a look at Google pages (http://pages.google.com/). You can upload raw files that are publicly available.

    Kalid — April 23, 2008 @ 12:31 pm

  14. Thanks! that will be fine. Btw replacing files e.g. on Google Code would be really useful, now you can only post a new file, so the url won’t be the same. That’s ok but not for bookmarklets.

    Brian — April 26, 2008 @ 6:48 am

  15. If you’re going to go the framed route, which we do with Wishlisting, you’re going to run into privacy issues in Internet Explorer if you use cookies. We overlay an iFrame and walk people through a short wizard when they add something to their wishlists. In Internet Explorer, we couldn’t make use of cookies to track their credentials until we instituted a P3P policy. Just a heads up for anyone running into odd cookie errors in IE… it’s time to read up on P3P :)

    Tom — May 1, 2008 @ 3:42 pm

  16. Hi Tom, thanks for dropping by :) . That’s a great point, I was going to start using cookies to remember settings in my own bookmarklets, didn’t realize that P3P would be an issue (never had to deal with it before).

    Kalid — May 1, 2008 @ 4:02 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Have a question? Know an explanation that caused your own a-ha moment? Write about it here.




Like it? Try All articles, RSS Feed or Email Subscription | Idea or suggestion? Contact me
copyright © 2007 Kalid Azad