26 December 2011

Bookmarklets: bookmark the convenience

Hello, Welcome to void main blog!

Today I am writing about the a tiny javascript program called bookmarklet. For those who aren't quite familiar with bookmarklets here is a little explanation.

What are bookmarklets?

Wikipedia says: "A bookmarklet is an applet, a small computer application, stored as the URL of a bookmark in a web browser or as a hyperlink on a web page". So, a bookmarklet is nothing but a tiny program normally written in javascript. Its source code is stored as the target of a browser bookmark.
Bookmarklets work on the page currently loaded on the browser. They can do lot of things using the information on the page. They can search the contents of the page, extract information from the page and present it in a different way, invoke external services to process the information of the page, to name a few.

We will explore some other amazing things we can do with bookmarklets later in this blog.

How do bookmarklets work?

Technically, a bookmarklet is just a URL. A URL consists of several parts: the protocol, hostname, path, etc. Based on the protocol, the browser decides how to handle the URL (if at all it can). For example, if the protocol is http:, the browser sends an http request to the host; if the protocol is file:, it retrieves the file on the local machine or network.
Most browsers also support a special protocol named javascript:. When a browser encounters javascript: protocol, it treats the rest of the URL as a javascript source code and executes it! Thanks to the browsers for doing this marvellous thing without which we couldn't have had the bookmarklets today! Bookmarklets make use of this feature of the browsers to work.

Bookmarklets have javascript: in the protocol part. The rest of the URL contains a javascript code that operates on the currently loaded page in the browser.

Let us take some examples. Here is a simple bookmarklet code:

javascript:(function(){
  alert('Hello, Good '
    + (new Date().getHours() < 12 ? 'Morning' : 'Evening')
    + '!');
})();

Copy the above code and paste on the address bar of your browser. You may need to remove the newline characters on some browsers (eg. IE). Its just a URL. You can do it on this tab itself. It won't navigate you away from this blog.
If you want to run it on a different tab and if you are on IE, make sure that you open some website before running the bookmarklet. IE doesn't like running bookmarklets from about:blank page.

Now press ENTER. You should see an alert wishing you.

Let us analyze the bookmarklet code. Match the parentheses and braces in the code to understand it correctly and easily. It creates a javascript function and invokes it. The body of the function is on the 2nd, 3rd and 4th lines. On the 5th line, we invoke the function.

This bookmarklet doesn't use the content of the current page. But it can do that. Bookmarklet code has access to the DOM tree loaded on the browser. Bookmarklet runs as if its code is written in the current page.

Let us take another example:

javascript:(function(){
  alert('This page has '
    + document.getElementsByTagName("a").length
    + ' hyperlinks');
})();

This bookmarklet accesses the document element of the current page, and counts the number of hyperlinks it contains.
The real power of bookmarklets lies in their ability to modify the DOM tree. The below bookmarklet clears your page and puts a new content on it. This time don't run it on this tab!

So, start a new tab (or window, if you still run the old IE6), open a website (for all IE versions), and run this:

javascript:(function(){
  d=document;
  b=d.body;
  while(b.firstChild)
  b.removeChild(b.firstChild);
  b.innerHTML='Bookmarklet Rocks!!!';
})();

You can notice that the content of the page changes. But, the URL of the page remains the same. You can check that by selecting your address bar and pressing Escape key. This resets the address bar to its actual URL. You can also refresh the page to see the original contents.
So, you have the tiny powerful bookmarklets and you have the html page to work on. With creativity and imagination (and a little javascript knowledge), you can do wonders.

What are the uses of bookmarklets?

Bookmarklets are a handy tool for performing a pre-defined operation on a web page. Those include:

Web Search

Bookmarklets can be used to search the words, phrases, etc. present on the page on web. This is possible because of the bookmarklet's capability to capture the user-selected text on the page. The exact way to capture the user-selected text varies across browsers, but both IE and Firefox support this. Once we get the selected word or phrase, we can redirect to a search url such as http://www.google.com/search?q=<SelectedText>.
This technique can be used to lookup online dictionaries, maps (interesting!), telephone directories, etc.

It is not always necessary to redirect to a search url. With little javascript coding, it is possible to open the result on an iframe. I believe this will achieve something similar to IE8's Activities!

Change the Look and Feel of the page

Bookmarklets are effective in extracting th data from web pages and presenting them in a different way. We can also change the styles to give the page a new look. This can be very useful for getting rid of annoying advertisements on some web pages.
To extract the data from web pages, XPath can be very useful. But unfortunately IE doesn't support XPaths yet. So, if you are making our bookmarklet IE-compatible, have to settle for document.getElementBys to extract the data.

Invoking external services

Bookmarklets can send/receive http requests asynchronously to external servers using XML Http Request. But, some workarounds will be required to address the security issues related to Cross-site Scripting.

Automating Tasks

Bookmarklets can be used to automate tasks such as filling web forms. Though there are tools (such as google toolbar) available which can automatically fill the forms for us, bookmarklets can do something more. They can fill the forms based on conditions instead of blindly filling the pre-defined values.
However, this will require the bookmarklet to be edited to specify the custom values. We cannot have a configuration file from where bookmarklets read these values. We will see more about this limitation in the next section.

And More...

The uses of bookmarklets are not limited to these. There are many more for you to explore.

Limitations of Bookmarklets

Bookmarklets too have limitations. It is after all a javascript program. So all the limitations of javascript (such as inability to access local file system) are applicable to bookmarklets also.
Bookmarklets cannot maintain a state, except on the web page. What I mean is, we cannot have a bookmarklet read the data we filled on the first page of a wizard and use it on the second page. This is because the only place a bookmarklet can keep its state is on the web page. When we navigate to another page, that state information will be lost. (If the wizard is ajax-based, we might be able to maintain the state because both the pages of the wizard will use the same DOM.)

Browsers place restrictions on the maximum size of URLs they support. Since the bookmarklets are stored as URLs, they are bound to be tiny enough to fall within that limit. I read somewhere that the limit on URL size for IE is around 2000 characters. However, Firefox supports longer URLs. But, in order to write bookmarklets that work on IE, the size of the bookmarklet source code must be kept within 2000 characters.

Some Useful bookmarklets

There is a good collection of bookmarklets on http://www.bookmarklets.com.

References

http://en.wikipedia.org/wiki/Bookmarklet
http://www.bookmarklets.com

No comments: