December 21, 2014
 
 
RSSRSS feed

Roll Your Own Custom Bookmarklets In Firefox, part 2

Javascript Bookmarklets

  • October 23, 2008
  • By Akkana Peck

In the last installment, I talked about the simplest form of "bookmarklets": bookmarks defined by Keywords and user-defined strings.

But you'll more often see the term "bookmarklets" used for a different sort of bookmark: those that execute Javascript code.

Javascript bookmarklets have been around since the early days of Javascript. They're possible because Firefox and most other modern browsers (except Konqueror) offer the special protocol "javascript:" to let you execute bits of javascript code directly.

For instance, try typing this into Firefox's URL bar:

javascript:alert('Hello, world!')

You've just executed some javascript code (Figure 1), of the sort you might include in a web page. But since it's packaged as a URL, you can bookmark it. That's a Javascript bookmarklet.

But what makes the javascript: protocol really useful is that the code is executed as if it was part of the current page. That means that you can access the information on the page, or even make changes to it. For example, try typing or pasting this URL:

javascript:void(document.body.style.color=prompt('Color?','green'))

The browser keeps the current page loaded. But in addition, a dialog pops up asking you for a color. Choose a color and click OK -- and the text of the current page changes (Figure 2). To turn it black again, use this link or click Reload.

Sitemap | Contact Us