May 26, 2016

Roll Your Own Custom Bookmarklets In Firefox, part 2 - page 3

Javascript Bookmarklets

  • October 23, 2008
  • By Akkana Peck

You can get bookmarklets for all sorts of specialized functions. There's an especially rich choice for web developers: bookmarklets to outline block elements, show or change a page's CSS, or validate HTML. See the links at the end of this article for some good bookmarklet sources.

If you know some Javascript, you can write your own bookmarklets. Just use the same techniques you'd use for Javascript on a page, with a couple of exceptions. First, you have to cram it all into one long "URL encoded" line, without line breaks, spaces or other characters that aren't allowed in a URL.

Return values are also important. Javascript that doesn't return anything, or returns an undefined type, will keep the current page loaded. If you return some other type, such as a string, the browser will load that string as a new HTML page. That's one way of loading a new page; another way is to set document.location to a new URL, like the Wikipedia and Babelfish bookmarklets in this article. Most bookmarklet authors sandwich their Javascript inside an "anonymous function", like this:

javascript:(function() { /* Bookmarklet code here */ })();

This also gives you the advantage of variable scoping: any variables you declare with var inside this function won't conflict with variables of the same name defined on the current page. Some people prefer to use if(1){ ... } around their bookmarklet code. Your choice.

You can do a lot with bookmarklets, whether you're writing them yourself or just using existing ones. Here are a few to start with:

Akkana Peck is a freelance programmer whose credits include a tour as a Mozilla developer. She's also the author of Beginning GIMP: From Novice to Professional.

Sitemap | Contact Us