# How To Make a Bookmarklet For Your Web Application

Get the Math, Better Explained eBook and turn Huh? to Aha!

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

• 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 &#038;& window.getSelection()) ||
(document.getSelection &#038;& document.getSelection()) ||
(document.selection &#038;&
document.selection.createRange &#038;&
document.selection.createRange().text));
}
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

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?

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?';
})();


Here’s how it works:

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

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.

## Other Posts In This Series

Kalid Azad loves sharing Aha! moments. BetterExplained is dedicated to learning with intuition, not memorization, and is honored to serve 250k readers monthly.

Math, Better Explained is a highly-regarded Amazon bestseller. This 12-part book explains math essentials in a friendly, intuitive manner.

"If 6 stars were an option I'd give 6 stars." -- read more reviews

1. Tiago says:

Thanks again for another useful post.

2. Kalid says:

Thanks guys, glad you’re finding it useful.

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

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

5. Aaron says:

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.

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

7. Brian says:

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

8. Brian says:

..some long term solution for this?

9. Kalid says:

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

10. Brian says:

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.

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

12. Kalid says:

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

13. nice post, can’t wait to build a bookmarklet of my own

14. Kalid says:

Thanks, hope it comes in handy for you :).

15. optimistx says:

Your ability to explain things clearly has already changed my life :). I had tried to learn about bookmarklets earlier, but now I started to understand their full potential. Perhaps too much possibilities so that browsers will soon make their usage impossible as it is already in https:// .
When your instacalc is used on a page with meta refresh tag with value eg. 300 seconds, the program disappears. Any way to prevent the refreshing programmatically?

16. Kalid says:

Hi optimistx, thanks for the comment! This post was buried under a slew of spam comments which I just cleaned up.

I didn’t know about the meta-refresh issue — I’m hesitant to block it since it may take away from the page functionality.

17. Sorry if this is a newb question, but Kalid, why do you wrap your bookmarklet js in a function? Personal taste? Particular browser compatibility? Here’s what I see in the instacalc js:

(function() {
[code]
})()

18. Chris says:

I was actually searching for something else but you’ve now got me thinking about how I can solve another problem I’ve been thinking about. Thank you.

19. Kalid says:

@Chris: Cool, whatever way it helps :).

20. Kalid says:

21. Ian says:

Excellent tutorial. This came in very handy.

One thing you might want to mention is that window.open() code will be blocked in imported scripts since its added to the page. However, the same code directly in the bookmarklet will _not_ get blocked since it is considered trusted.

22. Handy article – was discussing Bookmarklets the other day for an application.

23. Maybe direct javascript works fine but I don’t like the 2000 characters limit. It’s such a pity – let’s use something dynamic.

Very useful post – instead of using var[space] you can actually create variables by passing them into the arguments of the function (variable a), or by overwriting the argument (variable b):

javascript:(function(a,b){b=a.style;})(document.createElement(“iframe”))

25. Mark says:

This is Really useful . Thanks!

26. Kalid says:

@Brunner: Yes, I prefer the dynamic approach for easier debugging & better flexibility (can change the code on the server).

@Adam: Neat trick! Yep, that works too.

@Mark: You’re welcome!

27. QuHno says:

The crunchinator based approach is not the best for bookmarklets. It breaks when you try to convert a script containing a modulo like this:

var a= 33;
a=a % 32;
alert(a);

It results in:
javascript:(function(){var a=17;a=(a2);alert(a);})();

The crunchinator strips whitespaces, so % 32 becomes %32 what is the escape sequence for the number 2. That will lead to wrong results if you paste it into the address bar (clicking on a bookmarklet is the same as pasting)

28. Kalid says:

@QuHno: Ah, great catch. One more reason to just load the script dynamically.

29. Riva says:

Thank you so much for the descriptive post!

30. Kalid says:

@Riva: You’re welcome!

31. One thing you might want to mention is that window.open() code will be blocked in imported scripts since its added to the page. However, the same code directly in the bookmarklet will _not_ get blocked since it is considered trusted.

32. Thanks, this has given me some tips towards making a bookmarklet for my utility that takes a Zazzle link and generates full HTML code for a product.

33. ekrem says:

I need to write a plugin for opera browser.Please can you send me an easy example such as Hello world example?
Best Regards

34. kalid says:

@ekrem: Sorry, I don’t really have much on browser-specific plugins. I’d search the Opera docs.

35. Malintha says:

I want to run script from my local file . I tried this in IE

But it not works ? Can you help me please

36. kalid says:

@Malintha: You may not be able to access local files. Also, you’ll have to use file:// instead of C:\

37. But the driver — if he or she is smart — is prepared for that possibility by wearing a safety belt and choosing a car equipped with
safety devices such as air bags and anti-lock brakes. Emissions laws are presently resulting in cleaner,
more efficient gas models that are also easier to start.
Modern saw technology offers potential owners two distinctly different
paths when it comes to what type of technology they want
their saw to operate with.

38. Mark says:

It appears that clicking a bookmarklet in older Internet Explorer browsers triggers the unload event. Anyone aware of a workaround for the “javascript:” links triggering that?

Thanks

39. Kevin says:

kevinf2002+betterexplained.com@gmail.com
@Mark on August 22, 2013 at 1:45 pm:
“… clicking a bookmarklet in older Internet Explorer browsers triggers the unload event. …”

Have you wrapped the script in a function like:
javascript:(function(){
X== your bookmarklet code here … ==X
)();

[the right parens ")" and the pair of curly-braces "{}" are necessary at the end.]

My understanding is that sometimes operations will return an “unhandled” value which could cause problems. Wrapping your code in a function should fix it.

40. Kevin says:

@Mark on August 22, 2013 at 1:45 pm said:
“… clicking a bookmarklet in older Internet Explorer browsers triggers the unload event. …”

[scratch my previous 2 posts... I gooofed =) ]

Have you wrapped the script in a function like:
javascript:(function(){

})();

[Note: the right curly-brace "}" followed by a right parens ")" and a pair of parens "()" are necessary at the end.]

My understanding is that sometimes operations will return an “unhandled” value which could cause problems. Wrapping your code in a function should fix it.