Creating Bookmarklets for Fun and Profit

Bookmarklets are just like normal browser bookmarks, but when you click one, instead of taking you to another web page, it performs some action on the web page you are currently on.

You have probably encountered bookmarklets in some way, whether it’s in a bookmarking service like Instapaper, or maybe a cool web design tool that manipulates your page in some way. What you may not realize is that it’s very easy to create bookmarklets. So easy that you can use them not only in your large projects, but you can build quick bookmarklets to help you automate tedious online tasks.

Bookmarklet Basics

A bookmarklet is simply a snippet of JavaScript code saved as a link.
When you click the link, or click the bookmark you created from the
link, it runs the JavaScript code on the page that you are currently
looking at.

So what can you do with that? Almost anything! Let’s start, however,
with a very simple example.

So let’s take a very simple piece of JavaScript, and create a
bookmarklet.

alert('This is a rather simple example...');

This typical snippet of JavaScript simply pops up a box that says “This
is a rather simple example…”

So let’s now create a link that executes this snippet.

<a href="javascript:alert('This is a rather simple example...');"> Show Alert </a>

So it looks kind of like a typical <a> tag. The href however is a
little different. Instead of a typical page url, it is our JavaScript
code, preceded by javascript:. This is what allows us to run our code.

If you click the link, you will get the popup. But if you drag the link
to your bookmarks toolbar, you will then be able to click that bookmark,
and execute the code on any page.

Interacting with the Page.

The previous example isn’t very useful, it just pops up the same old
message each time. The beauty of a bookmarklet is that it runs the code
within the page you are viewing. This means your bookmarklet’s
code has access to all of the page elements, variables, and functions on
that page. This is also the reason to be careful using 3rd party
bookmarklets, they can also do malicious things like retrieve your
cookie from the page you are on and transmit it elsewhere.

Let’s jazz up our example to popup the title of the current page.

<a href="javascript:alert('This page is : ' + document.title);"> Show Title </a>

Now this link and bookmarklet will tell us the title of the current
page. This is because the document will be the page document of the
current page.

We can do much more than just get information and pop it up in an alert,
we can apply styles to a page, add or remove elements, or even
manipulate forms to automate data entry.

If you have some long form that is tedious to fill out, but the
actions you want to take can be automated, bookmarklets can save you a lot
of time. Better yet, you can create a bookmarklet for a coworker and be a
hero who saved him or her hours of work by simply spending a few minutes
creating a bookmarklet to help.

If you are making a bookmarklet to work on a particular site, there is a
good chance that the site uses jQuery (it’s that popular). If it’s another
framework you could utilize that too. If you know jQuery is on the page
you are using your bookmarklet for, it makes building bookmarklets that
much easier.

Here is a simple example. Sometimes when confronted with dozens of checkboxes on a page, I want to
just check them all, and maybe uncheck the few that don’t apply to me.
If there is no “Check All” button, I have to do it myself.
The code for that is simple, assuming you have jQuery on the target
page.

$(':checkbox').attr('checked', true);

This selects all checkboxes, and checks them all. Just throw code in a
link, drag the link to you bookmarks bar, and you’re ready to go
checkbox crazy at a moment’s notice.

Workflow

Often when creating bookmarklets, the code requires some
experimentation, and several JavaScript statements.

Here is the workflow I use.

Step 1: Experiment in the Dev Tools or Firebug

Since your code will run on a page, pick out a target page, and open
the JavaScript console of your Dev Tools, or Firebug. This allows you to
experiment with the JavaScript code and what CSS selectors can be used to select elements (if
you are using a framework like jQuery, as shown above).

You may want to write the code snippet in a text editor, then copy and
paste it into the console, rather than try to form you statement(s) in
the console itself.

Once your code does what you want, move to step 2.

Step 2: Prepare Your Code

Since you will have to place your code in the href attribute of an
<a> tag, there are some formatting restrictions. First take note of
any quotes in your code. I like to use only single quotes in my
bookmarklet code, so when I wrap the code in double quotes to embed it
in the HTML, I don’t break out of the href value.

Your code should also be compact. You can do this fairly easily by
removing line breaks. Make sure you are using semicolons properly, but
you already do that, right? You could also try using a JavaScript
minifier to reduce the code, but if there is that much code, you may
want to try a different technique, I will explain shortly.

Step 3: Create the Bookmarklet

There are two main ways to add a bookmarklet to your browser. You can
create an <a> tag on a page, and drag it to your bookmarks, or you can
create a normal bookmark to any page, then edit its title and link. You
would then set the like location to your ‘javascript: …’ code. This
strategy can be a bit cumbersome, but editing an existing bookmark is
the way you have to do it on iOS.

I prefer to create a link on an HTML page. This makes it easier to
share.

We saw the syntax for this at the beginning of this article.

It’s an <a> tag. The href is in the format "javascript: YOUR CODE
HERE"
and the content of the tag will be the title of the bookmarklet.

You can either create a new HTML page to create this link, or you can
use something like jsFiddle to quickly create
your link. This has the added benefit of making it easy to share with a
coworker, a friend, or the world.

Bigger Bookmarklets

If you are creating a bookmarklet that goes beyond a simple gimmick or
time saver, you may have a lot more code. While you can cram quite a bit
of code in that link, it’s often better to instead create a JavaScript
file that is hosted on the web, then have the bookmarklet load that
script into the page. Your script will execute in the page just as it
would have with the shorter bookmarklets.

Creating an external file has the added benefit of being able to update
the logic of the bookmarklet by simply updating the target file.

The readable version of the code looks like this.

(function () {
  var script = document.createElement('SCRIPT');
  script.src = 'http://example.com/the_code.js';
  document.body.appendChild(script);
})()

This creates a <script> tag, sets its src, and adds it to the page,
which will fetch and run the file immediately. Of course you would
change the value of src to be the url to your JavaScript file.

The whole thing is wrapped in a function that will execute immediately.
This is because we are creating a variable called script. Since we are
going to be running this on another page, we don’t want to accidentally
mess up a global variable that page may be counting on. By wrapping it
in this self executing function, we keep all our variables to ourselves,
not messing up the target JavaScript environment.

Ultimately the code is compressed to this:

<a href="javascript:(function(){var script=document.createElement('SCRIPT');script.src='http://example.com/the_code.js';document.body.appendChild(script);})()"> Do Something! </a>

Use Your New Superpowers for Good

Now that you can make bookmarklets, you can add all sorts of features to
any site you want. You are now a developer for any site on the web.

Almost anything is possible when you can run JavaScript on a website. If
you want to learn about what is possible with JavaScript, check out the
JavaScript and jQuery lessons on
Treehouse.

Update: A real-life example

I was watching the iOS videos on Treehouse, and coding along when I realized what I would like is for the video to pause when I tab over to Xcode, then resume when I come back to Treehouse. Since I work for Treehouse I could have easily added it to the feature development list, but I wanted it right away. So a bookmarklet was born.

You can check out the bookmarklet here. The code was built for use on a Treehouse video page, but it should work on any page with HTML5 video and jQuery.

Free Workshops

Watch one of our expert, full-length teaching videos. Choose from HTML, CSS or WordPress.

Start Learning

Treehouse

Our mission is to bring affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world.

Comments

12 comments on “Creating Bookmarklets for Fun and Profit

  1. Awesome!  This is extremely useful info… heard of bookmarklets, but totally overlooked the details until this post!  Thanks for writing about it.

  2. Great tutorial, and exactly the kind of thing that will lead to me clicking through to a subscription!
    Can you tell me how difficult it would be, on a scale of 1-10, to build a bookmarklet that would allow one to select text from a webpage and have that text automatically appended as an item to an XML (as in RSS) file? Google Reader had a bookmarklet that would do something like that but they put the kabosh on it recently and I’m really missing it.

    • @ef556a7599dbfa2c5701f8e56cc72b20:disqus gave a pretty overview. Getting the selection is possible, but not as straightforward as you would hope, nor cross browser.

      You would have some sort of web service to consume the snippet and add it to whatever xml file you are talking about. Remember that the bookmarklet runs on a different domain than your web service, so you have to work around that. Using jsonp is an option, but it will be a GET request, which is probably not ideal, particularly if you are sending a lot of data.An option to POST the data across domains effectively is to use JavaScript to construct a form with the action being your endpoint, method is post, and target is an iframe you have also created with JavaScript. Then you can fill in the form and submit it. It will POST to your service without changing the page in the host window. The downside is the web service can’t easily communicate back to the calling page, due to cross site restrictions, but you may not need it. 

      • That’s quite clever… I guess I need to remember that you can totally alter the DOM using bookmarklets.  I ran across the spec for CORS a while back, which allows for cross-domain POST requests; however, you do have to be able to add a custom HTTP header in your server’s config.  Personally, I don’t really want to open up my servers to CORS, even though it supports authentication, etc.  Maybe I’ll change my mind someday, idk.
        So, here’s a question – from an admin perspective, as cool as bookmarklets are, I’d almost like to prevent in-house users from running them, mainly on certain secure websites of ours.  I looked into the NoScript plugin for Firefox, but that seems too restrictive to be a realistic option – but I haven’t found anything that’s much better.  I haven’t really looked for IE yet.
        Thoughts?  Suggestions?  I know users don’t like being locked down, but a malicious bookmarklet could definitely affect operations negatively.

  3. @jimrhoskins:disqus Under the “Bigger Bookmarklets” heading, the readable example code has “createelement”, which won’t work – should be “createElement”.
    @domainnoob:disqus I know you’re not really asking me, but at any rate, I’d say for an experienced web developer, about 4 or 5 out of 10 for difficulty.
    The basic functions/components would be:
    1) Create a function to grab the selected text.  This varies by browser.  If you’re willing to copy and paste the text into a prompt(‘Paste text here’) dialog, it would avoid the cross-browser issues.
    2) Send a GET request, presumably using AJAX/JSONP, to whatever server (probably your own) hosts the RSS feed.  JSONP allows for making AJAX calls to servers other than the one you’re currently on.
    3) Make a server-side script in PHP/ASP.NET/whatever to access the RSS feed and update it with the new RSS item.  You could even add a hyperlink to the page the text is on, by reading the request header from the AJAX call (or just sending document.location to the server in the query string, though that’s probably redundant).

    I should note that, if you’re adding copyrighted content to an RSS feed of your own, there should be attribution to the original source, and even that might not be enough in some cases.  Also, if it’s a secure site or requires a login, I wouldn’t add it to an RSS feed.  The RSS hyperlink wouldn’t work anyways if it requires a login.

    • Thanks for pointing out the typo. Something happened to my code when I converted it from my markdown source where it lowercased all of the code snippets. I must have missed that when correcting it. I have updated the source.

  4. What about security? What are the security implications? If you add third party bookmarlets aren’t you taking a big risk?

  5. Hi guys,

    Newbie question here … I need a bit of help with the below bookmarklet. It generates a text area which include the pagetitle, the page url and the domain name. I need to break the text into two lines between the page title and the url and, at the end of the generated text (insert 1-2 line breaks) and include the tags of the post/page where the bookmarklet is ran (I am looking at using this bookmarklet on WordPress blogs).

    Can anyone please help with adjusting the below code?

    javascript:prompt(“URL and title:”, document.title ‘ – ‘ document.location.href ‘ – ‘ ‘ via ‘ document.domain.replace(‘www.’,”));void(0)