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 and the content of the tag will be the title of the bookmarklet.
HERE"
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.



Comments