Create Bookmarklets – The Right Way

Create Bookmarklets – The Right Way

Tutorial Details
  • Topic: JavaScript
  • Difficulty: Beginner
  • Estimated Completion Time: 30 minutes

Bookmarkets can be defined as mini applications masquerading as tiny snippets of JavaScript awesomeness that reside in your browser and provide additional functionalities to a web page.

Today, we’re going to look into creating bookmarklets from scratch and on the way, some best practices to follow.


They’re not for the nerdy, in fact, they’re pretty user-centric.

We’re always looking at ways to enhance our browsing experience, be it widespread or little known. Bookmarklets, I used to think, belonged to the latter – the bastion of super nerds. Much to my chagrin, I discovered that I was completely wrong about the topic. They’re not for the nerdy, in fact, they’re pretty user-centric, implement a lot of pretty neat functionalities and, just as people predicted, it’s become a core part of the way I interact with the browser — and the internet.

Today, I’d like to walk you through developing bookmarklets implementing some nifty bookmarks. Yes, bookmarks. We’ll be building more than one, albeit quite tiny ones. Intrigued? Let’s get started!


So What Exactly are Bookmarklets?

To quote my article intro:

Bookmarkets can be defined as mini applications masquerading as tiny snippets of JavaScript awesomeness that reside in your browser and provide additional functionalities, with just a click.

The word itself is a blend, portmanteau for the pedantic, of the words bookmark and applet. Also called favelets, these tiny snippets of JavaScript let you conjure up additional functionality for any page you’re visiting.

Because they consist of just JavaScript, they’re pretty portable — they’re supported by all browsers on all platforms, even on mobiles and tablets. Installing them is as simple as dragging them to their toolbar!


Yeah, But What’s the Point?

The point is that bookmarklets let you do a lot of things that are otherwise too developer-centric to achieve. Every functionality you get with a bookmarklet can be duplicated using a browser’s console and a little time. Bookmarklets merely simplify the process — packaging up the code that implements some functionality inside a neat little button.

Bookmarklets can be broadly categorized into a number of categories:

  • Ones that pass on data. Bookmarklets that submit a page to a service fall under this category. Bookmarklets dealing with social media, dictionary lookups, searches all fall under this category. We’ll be building one that submits to Reddit.
  • Ones that obtain information and/or modify the current page. We’ll be building a bookmarklet that sets a page’s background color.
  • Ones that works behind the scenes. A bookmarklet that erases any cookies of the current site is a prime example and one that we’ll be building.

#1 – Getting Started

The first point that you’ll need to remember is to prefix all JavaScript code with the javascript URI. Browsers have implemented this specific prefix so that the content followed by it can be treated, and parsed, as proper JavaScript code.

For example, clicking this link – see its code below – will alert a text.

<a href="javascript: alert('Linky text');">Linky</a>

#2 – Use an Anonymous Function as a Wrapper

Remember that your code will run against the currently loaded page — a page that probably will have JavaScript of its own and all the resulting collisions that it implies. The last thing that you need is to have your bookmarklet break the current page.

Wrapping up your code neatly inside an anonymous function will make sure that there are zero naming collisions. Additionally, JavaScript noobs will be flummoxed and will think you’re a god, if you’re into that sort of thing.

javascript:(function(){// your code here })();

This is pertinent when you’re using JavaScript elsewhere as well. Always, always insulate your code.


#3 – Externalize, if Needed

A bookmarklet needn’t necessarily be tiny, you’re free to go as big as you want. In those cases, in the interest of distribution and keeping your code upto date without manual user intervention, it’s best to create a wrapper that pulls in code as needed.

javascript: (function () { 
	var jsCode = document.createElement('script'); 
	jsCode.setAttribute('src', 'http://path/to/external/file.js');      			
  document.body.appendChild(jsCode); 
 }());

That’s pretty much what the above code does — it creates a script element, sets the source to a file hosted elsewhere and finally appends it to the document. This way, whenever a part of your code changes you can deploy your changes to a single source and have it instantly propagate to every user.

Note: You aren’t limited to doing this for JavaScript alone. If your bookmarklet makes use of a front end, you’re free to pull in the HTML and CSS externally as well, making your bookmarklet truly self updating.


#4 – Exercise Caution when Adding a Library

Again, if you’re building a behemoth of a bookmarklet, you may have need for one of those JavaScript libraries. But using them in your page isn’t as simple as merely including it — you’ll need to make sure that the libraries isn’t already available. Libraries like jQuery and MooTools dominate the market and you’d do well to make sure it’s not already loaded.

Another issue is that the page may have loaded another library which may lead to conflicts over the control of the $ symbol. Version collisions may also come into play at some point so keep that in mind as well.

Here is a quick shell for the code I generally use. Remember, in your production code, you’ll need to account for the issues I’ve mentioned above.

if (!($ = window.jQuery)) { // typeof jQuery=='undefined' works too
	script = document.createElement( 'script' );
   script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; 
	script.onload=releasetheKraken;
	document.body.appendChild(script);
} 
else {
	releasetheKraken();
}

function releasetheKraken() {
	// The Kraken has been released, master!
	// Yes, I'm being childish. Place your code here 
}

The code should be fairly self explanatory. Let’s run through it quickly anyway.

  • First up, we determine whether jQuery is loaded by checking whether the jQuery object exists in the namespace.
  • If not, we quickly prepare it for inclusion. We follow best practices and load it up from a CDN. Finally make sure to point to the main function containing the code to be executed.
  • If it’s already included, merely run the main wrapper function.

If you’re looking to avoid all this hassle, I highly recommend Ben Alman’s excellent bookmarklet generator. It takes care of namespace and versioning conflicts in a very clean manner. Good stuff!


#5 – Don’t Mess up the Parent Page, Unless you have to

Bookmarklets are useless if they, unintentionally, break a page.

I can’t stress this point enough. Bookmarklets are useless if they, unintentionally, break a page. And worrying about JavaScript isn’t the only thing you have to deal with.

If you have a front end, the HTML and CSS comes into play as well. Do not assign your containers and classes generic names — if you name it ‘container’, you’ll forever have my undying hate.

An easy way is to prefix [or suffix, I don't mind] everything with a bookmarklet specific string. And when writing your CSS, be very, very specific. Making use of cascading is nice but use it with ultra precision. Having styles leak over to the main page is irregular and doesn’t evoke confidence.


#6 – Test, Test, Test

If you’re building a smaller bookmarklet, one where including a third party library seems pointless, you’ll run into an ever present demon — cross-browser compatibility.

Might seem pretty obvious but this is something a lot of people forget, a lot of times. Make sure you test across as many browsers on as many platforms as possible.

Another easy trap to fall into is a bookmarklet that is meant to work on all sites that only works selectively. Pages can have different hierarchies and make use of different methodologies. Some sites may embrace HTML5 and use the related containers while other may play it safe and use generic divs. While mining for information, make sure to account for every school of development.


And Off We Go

Now that we’ve looked at some points to keep in mind during development, we’re going to build the three bookmarklets I talked about previously — one belonging to each category.

  • A bookmarket that submits to Reddit
  • A bookmarket that clears cookies of the current website
  • A bookmarklet that changes a page’s background color

If you’re already familiar with basic JavaScript, the following code should be a cinch– they’re only a few lines of code! The bookmarklets below have been with me for quite some time now and I can’t seem to find out where I originally saw them. If you do, leave me a quick note in the comments and I’ll add credits accordingly.


Bookmarklet #1 – Submit to Reddit

We’ll start off with a super easy one — submitting to an external service, Reddit in our case.

javascript:location.href='http://www.reddit.com/submit?url='
								+encodeURIComponent(location.href)
								+'&title='+encodeURIComponent(document.title)

This is some pretty simple stuff, taken right from the site. No anonymous wrapper or namespacing since the functionality is pretty limited.

When the bookmarklet is invoked, the following takes place, in logical order:

  • The page’s title and URL are captured using location.href and document.title
  • To make sure no illegal characters sneak in, we encode it using the encodeURIComponent method
  • Finally, we concatenate everything to get our URL and change the page’s location to it

This pattern works pretty much for most searching and submitting purposes. The only variable here would be the URL you submit to — each application takes a different approach. Under a minute of searching should see you through.

For example, a validating bookmarklet would look like so:

javascript:location.href='http://validator.w3.org/check?uri='+encodeURIComponent(location.href)

Note that we merely discarded the page’s title and changed the URL structure to point to the W3 validation service.


Bookmarklet #2 – Change a Page’s Background

javascript:void(document.bgColor=prompt('Color? Hex or name will do. May I suggest pink?','pink'))

This is just as simple as it looks. To keep things super simple, I’ve opted to not introduce variables and validation. We’ll just look at the core code.

  • First up, we create a prompt that asks the user for a color to set the background to. Since we’re not checking the input, I’m relying on you not being naughty.
  • Finally, we set the background to the chosen color through document.bgColor. That’s it!

Yeah, I know bgColor is deprecated and yeah, I know I should feel dirty but this will do quite adequately since a quick test on modern browsers came out positive.

You can play around with these quite a bit. This is similar to how you’d generally apply CSS styling to elements through JavaScript. We’re just applying it to arbitrary pages. Do make note that different pages have different structures so if the page has a full wrapping container, the effect may be meaningless. In these cases, you may have to hunt for the main container and then apply the styling to it.


Bookmarklet #3 – Clearing cookies

javascript:function(){
	var c=document.cookie.split(";");
	for(var i=0;i<c.length;i++){
		var e=c[i].indexOf("=");
		var n=e>-1?c[i].substr(0,e):c[i];
		document.cookie=n+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
	}
}()

Not really as complicated as it looks — cookies merely have a very strict syntax so we’ll need to parse it step by step. Let’s go through the code:

  • Split document.cookie based on semicolors. c now becomes an array containing all the cookies set for the current domain.
  • Loop through the array.
  • Check whether the cookie contains the equal to symbol i.e. whether a cookie value has been set and returned
  • If yes, we’ll capture all information just upto it. If not, let the cookie be as it is
  • Finally, add a string value which empties the cookie’s value along with defining an expiry date from the past, effectively erasing it

Remember, bookmarklets still operate under the page so you can’t access cookies from other domains. You’re limited to the page you invoke the bookmarklet on.


That’s a Wrap

And we’re done. Remember, we’ve merely scratched the surface of bookmarklets. A lot of them are complete applications within themselves, with a proper front end to boot. Those take a lot of time and planning to build, just like any non-trivial application. This was merely to get your foot in the door of bookmarklet development. Hopefully you’ve found this tutorial interesting and this has been useful to you.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Thank you so much for reading!

Siddharth is Siddharth on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Sahan

    Nice one, thank you!

  • http://www.mlabs.info Samuel Marian

    Thanks dude, i’ll try it! :)

  • http://hultner.se Alexander Hultner

    This is a lot like greasemonkey development. The difference is that the user trigger the javascript with bookmarklets and with greasemonkey it’s added at page load. In that way greasemonkey is more suitable for targeting a specific site while bookmarklets are better for portable scripts for multiple sites. Anyway nice article.

    • http://www.ssiddharth.com Siddharth
      Author

      Yep, Greasemonkey scripts are more single site focused. Plus there’s the fact that it’s browser limited while bookmarklets are pretty portable.

      Thanks for reading!

      • http://hultner.se Alexander Hultner

        Yeah greasemonkey are browser limited but not by far as limited as they used to be, there’s pretty good native support in Opera, Chrome and Safari and there’s addons to IE in order to get it to work. However as mentioned in this article bookmarklets can be pretty much for anyone because of their ease of use while I’d say greasemonkey scripts are more targeted to users above the average internet user. At least that’s my opinion.

  • http://www.sz-media.org Nico Poggenburg

    I saw something like that for SEO. A JS Bookmark for checking the Backlinks with the Yahoo Tool. Was quite nice.

    • http://hultner.se Alexander Hultner

      That’s an cool idea. I made a bookmarklet for my younger brother a while ago which let him click the bookmark, choose an “featured image” and then it added the site to his custom startpage with the image as a thumbnail, kinda a bit like the “speed dail” pages of Chrom(e|ium) and Safari.

  • http://adevtus.com Adevtus

    I’ll admit I was a little confused at first, that is, until I ran that W3C validator example. I had no ideea you could run javascript via bookmarks. I’m thinking of coming up with some examples of my own.
    Good article, thanks!

  • http://magentix.be Kristiaan Van den Eynde

    I would be careful with advising people to use a bookmarklet that loads an external script. If someone gets hold of the host, everyone using the bookmarklet will be at risk.

    As a small sidenote, shouldn’t this:
    // typeof jQuery!=’undefined’ works too

    be this?
    // typeof jQuery==’undefined’ works too

    • http://www.ssiddharth.com Siddharth
      Author

      My, my. Edited. Thanks for spotting it!

  • http://elundmark.se/ elundmark

    Does anyone know of a good regex pattern to make the compression? ” & -> & , ” -> " , and deleting the right spaces, plus deleting all tabs? Can’t seem to find any solution…

    ——-

    Also, I hate being a typo narc, but I couldn’t help noticing 2 errors in section #3‘s code. The closing tag of the function, and the ref. to jsCode which is mistyped as elem. Rows 3 & 5.

    javascript: (function () {
    var jsCode = document.createElement(‘script’);
    elem.setAttribute(‘src’, ‘http://path/to/external/file.js’);
    document.body.appendChild(jsCode);
    }());

    Should be

    javascript: (function () {
    var jsCode = document.createElement(‘script’);
    jsCode.setAttribute(‘src’, ‘http://path/to/external/file.js’);
    document.body.appendChild(jsCode);
    })();

  • Holger

    Holy cow, I wasn’t aware a bookmarklet can just read cookie values. Doesn’t that allow for writing a cookie that just transmits the session cookies of any page it is invoked on to some remote server?
    If that is the case, you should be really really careful if you trust the source of bookmarklets you use.

  • sidd

    Hey is there any tutorial to add an ajax upload to worpress theme admin panel? I want to add this upload button for uploading slider images… Is there any way I could do it? Please let me know….

  • DJ

    Please forgive the “newboid” question – let’s say I’m ecstatic with the idea of deleting cookies for the page that I’m on, and would be perfectly happy to accept the functionality exactly as you have described it here; which I am.

    And let’s say that I’m using Firefox – which I am. And (here’s the simple part that I realize wasn’t the intent of the article to teach, and probably should be embarrassed to ask in a forum like this if I knew any better) How does one get it to actually work in the browser. You did say to “drag to the tool bar,” but I’m not sure of the specifics of how to accomplish that – i.e. is there a place where I can just cut and paste this code into a browser and have it added? Or, lets say that I want to offer a “bookmarklet” like that on a blog. How would that be possible, i.e. what entity would I box it in that a reader would just “drag” to his/her toolbar? A text box, a link, etc?

    I have a feeling that this is a very beginner type question for a forum such as this – but you did ask for comments; and, you really have piqued my interest enough to do it. Good article – everything you wrote was clear and understandable, it’s just my level of background that is the problem.

    • Mat

      Just drag the link from #1 – Getting Started to your tool bar and try to click it. ;)

  • annmarie

    Why didn’t you anonymize your 3 examples? Anyway, I’ve been using the bookmarklets from https://www.squarefree.com/bookmarklets/ which have been around for ages.

    • http://www.ssiddharth.com Siddharth
      Author

      Because by the time you’re reading the examples, it’s fairly apparent? I didn’t want to include redundant code in the examples. :)

  • Alex Evans

    Nice article. One of the best bookmarklets i saw was the jquery themeroller one. Its a good example of injecting external scripts (css in this case) into a page.

    Also, In the “Externalise if needed” section,

    shouldn’t
    elem.setAttribute(‘src’, ‘http://path/to/external/file.js’);
    be
    jsCode.setAttribute(‘src’, ‘http://path/to/external/file.js’);

    • http://www.ssiddharth.com Siddharth
      Author

      Fixed. Thanks.

  • http://www.tutorialchip.com/ Qamar

    Very informative.
    Thanks,

  • http://tutorial-city.net/ Eduardo Matos

    Bookmarklets can be very dangerous to the end user, because an attacker can inject some useful code mixed with some malicious code, and I don’t know any way a website could detect and defend itself from this kind of attack. Any ideas?

    • http://magentix.be Kristiaan Van den Eynde

      If you put all of your code in an IIFE, the only thing they can still manipulate is whatever is left in the global (window/document) scope.

      Don’t let that fool you, though. Cookies, for instance, are stored in the global scope and could be very dangerous once stolen. Which is why I would strongly advise against using bookmarklets that are developed by untrusted sources or that load external scripts.

  • lafncow

    @DJ: the bookmarklet code takes the place of a url. So to manually create one, just create a new bookmark in your browser and set the url to be the code of your bookmarklet. To share it on a webpage, just create a link that has the bookmarlet code in the “src” property instead of a url. Done. :)

  • http://www.hechtmediaarts.de/ Andreas Hecht

    Nice Article, thank you for that!

  • http://stateoftomorrow.tv D

    Too bad neither of the examples actually work :-(

  • Tiko

    Hmm, what is this?

    if (!($ = window.jQuery))

    An assignment? I don’t get it.

    Shouldn’t it be like this?

    if (($ != window.jQuery))

    I am too noob maybe…

  • M1573RMU74710N

    Similar to the error already pointed out, the line:

    if (!($ = window.jQuery)){

    Needs to be:

    if (!($ == window.jQuery)){

    I’d also recommended following the jQuery style guidlines

    So the line would be written thusly:

    if ( $ !== window.jQuery ) {

    Although personally I tend to deviate from the guidelines on one point and use !() rather than !==, as you do.

  • M1573RMU74710N

    Oh, I forgot…

    Also, it needs to be:

    if ( !(window.$ === window.jQuery) ) {

    or
    if ( typeof $ === “undefined” ) {

    The code as written will throw a Reference Error if $ has not been declared on the page. (accessing a non-existent property of an object just returns undefined, not a reference error).

  • M1573RMU74710N

    Darn, I wish I could edit comments…or maybe I should review more carefully before submitting ^_^

    Anyway, if you do change it to check if typeof is undefined, you still have to determine if it is in fact jQuery, so my previous example would need to be something like :

    if ( typeof $ === “undefined” || $ !== window.jQuery ) ….

    • mofle

      Or you could just use

      if ( window.jQuery ) {

      }

  • http://www.thingsthatnevergotmelaid.com/ Chris K

    Thanks for this, great post.

  • azend

    Cool article but if you do a follow up can you cover XmlHttpRequests and cross domain scripting inside of bookmarklets?

  • http://www.ibantencom ibanten.com

    nice tutorial….. i’m looking for this bookmarklets… thank you so much…

  • http://realcostdomains.com Steve

    Thanks – could have used this on a project last month, time to go add part of it in…

  • Peter

    The most important bookmarklet of all times: found at http://www.cornify.com/ XD

  • http://www.magnet4marketing.net Fabrizio Van Marciano

    Very good tutorial, easy to understand as always, thanks.

  • http://www.think360studio.com/ Think360 Studio – Web Design Company

    Nice really article. thank you so much

  • http://colmjude.com Colmjude

    Thanks for another good article.

    One thing that would make it even better is if some links to good quality more advanced tutorials had been provided so that those that have got the taste can carry on learning.

    Has anyone got some suitable follow on links?

  • http://tif.ca Tiffany Conroy

    Should I feel flattered that this reads like a redux of my article at http://rootcamp.io ?

  • http://www.netdevo.com Leo

    The Motorstorm Web Apocalypse game is one the best examples I’ve seen of what can be done with bookmarklets!

    It combines HTML5, CSS3, JavaScript and Bookmarklet technologies to create an interactive physics driving game where people can drive in their Facebook profile and YouTube video pages.

    It really pushes the boundaries of what’s possible with current open web technologies! Interesting to note such execution would be impossible using Flash!

    http://www.motorstorm.com/webapocalipse

    ps: Obviously this will not work on IE browsers (might run on IE9). But runs really well on Chrome, Safari or Firefox.

  • http://nlsmith.com/ Nathan L Smith

    js2bookmarklet is a ruby gem with a quick script to convert a script to a bookmarklet. It’s on rubygems or https://github.com/smith/js2bookmarklet

  • http://www.rickgrossman-blog.com Rick Grossman

    I have been trying to create bookmarklets for some time without much success. Thank you for the great explanation.

  • http://fiveholiday55.blogspot.com Helen Neely

    Nice tip for some of us starting out with Javascript. It was quite easy to get it running.

  • T Binsted

    Thanks. The anonymous function part was what sealed the deal where other examples hadn’t.

  • http://avonture.be/allevents/ cavo789

    Thank you for this excellent tutorial. Really clear and giving many ideas.

  • laccy

    http://marklets.com/

    a lot of nice bookmarklets for development, graphic and other stuff
    i had many extensions, for chrome the background pages eat too much, so i replaced many of them with bookmarklets

    translation, html to csv, megavideo bypass limit, bitly sidebar, css sprite, editor, site editor, color picker, site info

    they are really nice and i use only when i need

  • http://www.bitbybitblog.com allie

    Thank you SO much for this great tutorial. You made things so easy for me! I got my bookmarklet up and running in a couple of days.

  • Bob

    “You aren’t limited to doing this for JavaScript alone. If your bookmarklet makes use of a front end, you’re free to pull in the HTML and CSS externally as well, making your bookmarklet truly self updating

    Can you explain how to do this or link to a page explaining it. Im using jquery and try to do a get. It works on my local sites but not on a external site… say twitter.

  • Deeps

    Thanks for this wonderful tutorial.. Its great, simple, clear and easy to understand. Thanks !

  • Alexander

    Nice tutorial.

    You might include the fact that single-line comments e.g. double-slashes //, will break a bookmarklet because (at least in Firefox) everything gets compressed to a single line at run-time.

  • http://twitter.com/mdcolceag Mihai Daniel Colceag

    my script won’t load, i have a simple function alert(“hello, i’m externalised!”); in the javascript file and the code that i have written is

    Click me! Alert!

    Anonymous Function!

    Externalize!!!

    href=”javascript: (function(){

    var jsCode = document.createElement(‘script’);

    jsCode.setAttribute(‘language’, ‘JavaScript’);

    jsCode.setAttribute(‘src’,'http://127.0.0.1/bookm/bookm.js’);

    jsCode.onload = jsCode.onreadystatechange = function()

    {

    alert(‘hello,i’m here!’);

    };

    document.body.appendChild(‘jsCode’); })();”>Externalize!!!

    • http://twitter.com/mdcolceag Mihai Daniel Colceag

      if i load the file via in the head section the file loads.
      Do you think you could help?

      • http://twitter.com/mdcolceag Mihai Daniel Colceag

        Done!

  • leosok

    A great resource to create your Bookmarklet is “http://ted.mielczarek.org/code/mozilla/bookmarklet.html”. It’s a generator which wraps your JS code in a function and minifiez it! Have fun!

  • chovysblog

    I noticed one major problem with your example loading jQuery — it does not enforce any particular version. So one page your bookmarklet is loaded on could be jQuery 1.6.1 (which doesn’t support a lot of things your bookmarklet might rely on) while another page may be even older.

    I need a way to check if its jQuery 1.9.1 and if not load that, while keeping the existing library intact using noConflict so the underlying page doesn’t break.

    I haven’t quite figured out how to do this yet….