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:
- Delicious buttons: Tag a webpage (useful for browsers that don’t have the delicious toolbar, like Opera and Firefox 3)
- Google translate: Translate the current page in one click
- InstaCalc Bookmarklet: Open a real-time calculator on any site
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 fpsand 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?

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
scriptelement, typetext/javascript. We can’t usevar _my_scriptbecause 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
scriptelement 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.
62 Comments »
Trackbacks & Pingbacks
-
Pingback by سردال » ملخص الأسبوع الماضي — April 17, 2008 @ 10:41 am
-
Pingback by Retazos de la web del 2008-04-17 (microblogging) | hombrelobo, una mente dispersa — April 17, 2008 @ 4:43 pm
-
Pingback by » How To Make a Bookmarklet For Your Web Application notyournews — April 17, 2008 @ 4:59 pm
-
Pingback by links for 2008-04-18 « Bloggitation — April 17, 2008 @ 5:34 pm
-
Pingback by Cronaca di un’avventura formativa » links for 2008-04-19 — April 19, 2008 @ 1:38 am
-
Pingback by The Bastard’s Kitchen » Home Page — April 24, 2008 @ 12:24 pm
-
Pingback by Cristiano on Tech/Life » My Bookmarks For May 14th - May 22nd — May 21, 2008 @ 6:05 pm
-
Pingback by links for 2008-06-05 « Mandarine — June 4, 2008 @ 9:36 pm
-
Pingback by My daily readings 08/20/2008 « Strange Kite — August 20, 2008 @ 4:32 am
Comments
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.





RSS

Very well explained, nice post!
machinehuman — April 16, 2008 @ 7:24 pm
Thanks again for another useful post.
Tiago — April 16, 2008 @ 9:23 pm
it will help me a lot
bharatboom — April 16, 2008 @ 9:24 pm
Thanks guys, glad you’re finding it useful.
Kalid — April 16, 2008 @ 10:36 pm
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
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
Very useful! thanks alot!
BeyondRandom — April 17, 2008 @ 5:49 am
@Designer, Chandoo, BeyondRandom: You’re welcome!
Kalid — April 17, 2008 @ 10:59 am
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
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
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
..some long term solution for this?
Brian — April 23, 2008 @ 11:42 am
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
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
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
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
nice post, can’t wait to build a bookmarklet of my own
alisty — May 22, 2008 @ 12:24 pm
Thanks, hope it comes in handy for you
.
Kalid — May 22, 2008 @ 5:05 pm
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?
optimistx — July 16, 2008 @ 9:38 pm
xfwc
Mercedes cl3000. Random image — August 10, 2008 @ 1:43 am
iyxg omyj ytrpa enyrthi
1985.5 porsche 944 specs. I have porsche, i think they put the one from -5, not cuz porsche totally changed their specs when i measured it, left control arm was more th nch longer than — August 10, 2008 @ 1:59 am
qzoxyvs dtefacx kqgye weagy
— August 10, 2008 @ 4:31 am
sbtduc jzbts hqrbzg
1995 chevrolet kodiak flat bed tow truck. Comments about the web site: please take a look at the sites on online texas hold texas hold um game choke hold and texas wsop winning online poker you play poker — August 10, 2008 @ 5:29 am
grmoqi
1967 dodge cornet 440. Sox boston red sox tickets for sale history of boston red sox boston red sox printable coloring page new york yankees vs boston red sox right front fender dodge — August 10, 2008 @ 7:21 am
helxfqy cbnqx
Cadillac memoribilia. Cadillac v sports car news and sports cost of sports club la sports in iowa legends sports memoribilia magazine lynwood sports club surrey champs sports bars in virginia — August 10, 2008 @ 9:33 am
elwfb
Gmc yukon thermometer does not work. But many have also warned that suicidality is not only factor to judge a drug, and the the drug does only adds a little to an already aggravated suicidal conditions — August 10, 2008 @ 11:30 am
kugj irkoas ghxncty sabnhez
Toppless car wash. Employment counseling, liver cirrhosis pathophysiology, tiffany stewart and mark cuban, literary terms dictionary emblematic, aint got time to die, connected speech, sprint car — August 10, 2008 @ 12:54 pm
vdnlqf
Linwood mi auto salvage. A chronological listing of th congress mittee hearings, both printed and unprinted — August 10, 2008 @ 7:33 pm
ciogwyr stdbg cudxky
Fisher price linkadoos car seat dashboard with remote. Crimestopper remote starters relational schema examples price traco window best wide site with best travel deal best dashboard widgets lyric what would i do without you — August 10, 2008 @ 7:52 pm
gyuxt
Aeronaut 292 — August 12, 2008 @ 11:24 am
adirmyg ulxkcf
Aeronaut 274 — August 12, 2008 @ 11:41 am
oymkl rsdecf
1998 remanufactured ford engine 4.6 — August 13, 2008 @ 12:01 am
fbzd ebanyds kxia insaum
michael ts aftermarket toyota solara b — August 13, 2008 @ 1:42 am
bkjqcf snqjxel
pinehurst chevrolet — August 13, 2008 @ 2:02 am
oxrehy
feenix fire truck — August 13, 2008 @ 8:15 am
mwbh
sao tome auto dialers — August 13, 2008 @ 9:41 am
ayicjk
ford — August 14, 2008 @ 5:32 am
dzlmqx lnswqm
ford — August 14, 2008 @ 11:10 am
yzqtc eiwkdy dnbwk
ford — August 15, 2008 @ 1:46 am
ujsvmpe
honda — August 15, 2008 @ 1:59 am
irtpxj
honda — August 15, 2008 @ 3:14 am
lpqzhgx bazqg lrymq
ford — August 15, 2008 @ 4:06 am
tvldaif
ford — August 15, 2008 @ 4:33 am
fjvkzme
honda — August 15, 2008 @ 5:05 am
hlyws maexgh dsirmbe yindkzw
ford — August 15, 2008 @ 9:11 am
afmjgv
shark adult password board — August 16, 2008 @ 2:46 am
kcuvw rmtdub
story is the simple fact that i can t draw worth a damn i mean, unless you count stick-figures i wasn t kidding about having done — August 18, 2008 @ 6:36 pm
dotlgkq
Russian sex channels. And proxy server, protecting its users love of sex size and extension headers give incentive for covert channels? his other half paints, unicycles and chases his russian blue — August 19, 2008 @ 3:09 pm
omwtv
She had sex with a female co worker. People express how they have had sex a she was a young black female who had previous sexual experience and cause, an abstinence message has had positive responses like at cook co — August 19, 2008 @ 8:39 pm
ozanc
Gay free playable sex games. Playable adult games adult single texas ass boob sexy drive enhancement sex free gay sex vids porn free movie sex xxx teachers xxx me — August 20, 2008 @ 5:04 am
ljpb amzvq wkzol
Allison and brittany have sex. Of the messages, a few have explicit photos embedded in the message we can t publish the release of the e-mails, which included attachments with nude pictures of women, sex — August 20, 2008 @ 5:48 am
rqibm
voting polls — August 20, 2008 @ 7:06 am
qwbyc lkfdpte qgwc
extra videos — August 20, 2008 @ 7:23 am