Better Living Through Bookmarklets

Share this article

Bookmarklets are a simple way of adding functionality to your Web browser, and can be a useful addition to your workflow as a Web developer.
In this article, I’ll point out some useful bookmarklets, provide tips on building your own, and demonstrate some advanced techniques for making the most of these powerful tools. A bookmarklet is a short piece of JavaScript embedded in a browser bookmark. The JavaScript is executed when the bookmark is selected. The magical thing is that this execution occurs in the context of the current page. The bookmarklet has access to the full document object model of the page and can modify it and use the information therein to launch new windows or redirect the browser to other sites. If you’ve never experimented with bookmarklets before, you should do so before reading the rest of this article. and both provide extensive bookmarklet collections, and Jesse Ruderman has arguably the most comprehensive bookmarklet collection on the Web at Jesse’s Web Development bookmarklets, in particular, should be a required addition to any Web developer’s browser. Bookmarklets work with all modern browsers that support JavaScript, but some browsers are more bookmarklet-friendly than others. Internet Explorer 6 for Windows suffers from an infuriating 508-character limit on the size of bookmarks, which seriously reduces the range of bookmarklets available for that browser, although a technique that I’ll cover later does provide a partial remedy. To get the full benefit of bookmarklets, I recommend you use a Mozilla-based browser such as the excellent Firefox, which also comes with a number of useful tools to aid bookmarklet development. One of the charms of bookmarklet development, however, is that the cross-browser concerns that frequently plague serious JavaScript development are avoided: there’s nothing wrong with developing a bookmarklet for a specific browser (especially bookmarklets for personal use), so developers can literally do anything that their browser will let them.
Common Bookmarklet Variations
If you’ve explored any of the sites mentioned earlier, you should have an inkling of the huge range of functionality that bookmarklets can provide. The simplest and most common variety of bookmarklet is the simple navigation bookmarklet, which takes the URL of the current page and passes it on to another site. Classic examples are “validation” bookmarklets, which redirect the user to an online HTML or CSS validation service for the current page. These bookmarklets are trivial to create, but can be adapted to some very useful ends. I’ve had a lot of fun creating “edit this page” bookmarklets for Websites that are powered by Web-based content management systems. Many such systems embed an ID in the URL of pages on the public site, directly corresponding to the ID used in the URL of the form for editing that page’s content in the site management system. An “edit this page” bookmarklet extracts the URL of the current page and uses it to instantly redirect the user to the edit interface for that page. For example, imagine a site with URLs like this:
The site also has a password-protected management interface, which offers an “edit page” interface at the following address:
An “edit this page” bookmarklet for the above site could be implemented thus:
This concept can be greatly expanded if you have some control over the content management system in use on the site. For example, in a site that doesn’t expose the internal ID of an article in the URL, you could instead serve the ID up in an HTML meta tag, which would then be available to an “Edit This Page” bookmarklet through the DOM. Many bookmarklets modify the current page in some way. Common examples include bookmarklets for “zapping” annoyances such as unwanted Flash animations or even images that are sized to common dimensions for banner ads. These can be fun, but are often limited by the need to be activated manually every time a page is loaded. More useful are bookmarklets that help Web developers analyse the structure of a page, or even modify the page structure, ‘live’. My personal favourite of these are Jesse Ruderman’s “test styles”, “edit styles” and “ancestors”, from his Web Development collection. The latter shows the HTML element hierarchy leading to the section of the page under the mouse cursor, which is great for figuring out how CSS can be applied to a page. The former two allow the CSS for the current page to be modified “live”, providing instant feedback on potential design changes. My Image Drag bookmarklet for Mozilla makes every non-background image on a page “draggable”, which can also be an aid when considering tweaks to a page’s design. One useful but frequently overlooked JavaScript trick is that entire HTML pages can be embedded in a bookmarklet. Try entering the following directly in to your browser’s URL bar:
javascript:'<h1>This is HTML</h1>'
The browser should display the rendered HTML from the string. It does this because the string is evaluated as an expression, the result of which is then displayed in the current browser window. The same trick can even be used to turn your browser in to an over-specified calculator:
javascript:1 + 4;
It can sometimes be useful to write bookmarklets that embed an entire page in this way, especially if they require a user interface more complex than simple confirm()
and prompt() boxes.
Assisted Text Entry
I spend a sizable portion of my time online staring at textarea boxes. The three blogs I update are all maintained through textareas, as are the sites I develop at work, and the various online forums I participate in. Textareas are everywhere. They’re also a far-from-optimal way of working with text, especially when compared with dedicated text editor software. Bookmarklets can make dealing with textareas significantly less painful, and can give them useful additional functionality. My favourite example of a textarea-enhancing bookmarklet is another one from Jesse Ruderman: Blogidate XML well-formedness — a Mozilla/FireFox bookmarklet, which checks that the text in every textarea on a page is well-formed XML and changes the background colour of the textarea accordingly. This is great for catching simple mistakes in XHTML before posting it to a site. Jesse also has a suite of HTML validation bookmarklets, which check the syntax of HTML fragments in textareas using the WDG validator. Another tool I use regularly is my expand HTML shorthand bookmarklet. This applies a sequence of simple conversions to text in textareas:
    1. Text blocks separated from each other by a blank line are wrapped in paragraph tags
    1. Lines starting with an = sign are converted in to <h4> headers
  1. Lines starting with an * become bulleted lists
= Header 
* list 1 
* list 2
 <li>list 1</li> 
 <li>list 2</li> 
A shorter version is available for IE. This version sacrifices the header support to fit within the 508 character limit: Expand HTML shorthand IE. Expand HTML shorthand: —- javascript:(function() { var tas = document.getElementsByTagName('textarea'); for (var i = 0; i < tas.length; i++) { var ta = tas[i]; var text = ta.value.replace(/(rn|r|n)/g, 'n'); var paras = text.split(/n{2,}/); for (var i = 0; i < paras.length; i++) { if (/^* /.test(paras[i])) { var lines = paras[i].split('n'); for (var j = 0; j < lines.length; j++) { lines[j] = ' <li>' + lines[j].replace(/^* /, '') + '</li>'; } paras[i] = '<ul>n' + lines.join('n') + 'n</ul>'; } if (/^= /.test(paras[i])) { paras[i] = '<h4>' + paras[i].replace(/^= /, '') + '</h4>'; } if (!/^<(p|ul|li|h4)>/.test(paras[i])) { paras[i] = '<p>' + paras[i]; } if (!/</(p|ul|li|h4)>$/.test(paras[i])) { paras[i] += '</p>'; } } ta.value = paras.join('nn'); } })(); —- Expand HTML shorthand IE: —- javascript:(function(){var tas=document.getElementsByTagName('textarea'),ta,t,ps,i,l,j;for(i=0;i<tas.length;i++){ta=tas[i]; t=ta.value.replace(/(rn|r|n)/g,'n');ps=t.split(/n{2,}/);for(i=0;i<ps.length;i++){if(/^* /.test(ps[i])){l=ps[i].split('n');for(j=0;j<l.length;j++){l[j]=' <li>'+l[j].replace(/^* /,'')+'</li>';}ps[i]='<ul>n'+l.join('n')+'n</ul>';}if(!/^<(p|ul|li|h4)>/.test(ps[i])){ps[i]=' <p>'+ps[i];}if(!/</(p|ul|li|h4)>$/.test(ps[i])){ps[i]+='</p>';}}ta.value=ps.join('nn');}})(); —- The unexpanded source (before whitespace removal) looks like this:
javascript:(function() {  
    var tas = document.getElementsByTagName('textarea');  
    for (var i = 0; i < tas.length; i++) {  
        var ta = tas[i];  
        var text = ta.value.replace(/(rn|r|n)/g, 'n');  
        var paras = text.split(/n{2,}/);  
        for (var i = 0; i < paras.length; i++) {  
            if (/^* /.test(paras[i])) {  
                var lines = paras[i].split('n');  
                for (var j = 0; j < lines.length; j++) {  
                    lines[j] = '  <li>' + lines[j].replace(/^* /, '') + '</li>';  
                paras[i] = '<ul>n' + lines.join('n') + 'n</ul>';  
            if (/^= /.test(paras[i])) {  
                paras[i] = '<h4>' + paras[i].replace(/^= /, '') + '</h4>';  
            if (!/^<(p|ul|li|h4)>/.test(paras[i])) {  
                paras[i] = '<p>' + paras[i];  
            if (!/</(p|ul|li|h4)>$/.test(paras[i])) {  
                paras[i] += '</p>';  
        ta.value = paras.join('nn');  
Tools for Bookmarklet Creation
You can create bookmarklets with nothing more than a text editor — or, if you’re really confident, you can type them straight in to your browser’s “New Bookmark” field. For anything more complicated than a simple navigation bookmarklet, however, it makes sense to take advantage of dedicated tools. If you’re using Firefox, you already have access to some useful aids for bookmarklet creation. Firefox’s JavaScript console is an invaluable debugging tool, and the DOM inspector is a great aid for exploring the DOM tree of a page when writing bookmarklets that modify page contents. Jesse Ruderman’s shell bookmarklet for Firefox and Mozilla provides an interactive JavaScript prompt attached to the context of the current page and is a great way to try out new techniques before you commit them to a text editor. While bookmarklets cannot contain line breaks, it’s essential that you keep your source code indented when you write anything more than a handful of statements. My remove linebreaks bookmarklet (below) is a tool that removes tabs, newlines and multiple spaces from a block of JavaScript. In many cases, this is all you need to do to create a bookmarklet from a simple block of code, although you must remember to terminate each line with a semi-colon before you convert it. The bookmarklet is also an example of an HTML page embedded in a bookmark. Remove linebreaks: —- javascript:'<textarea rows=%2220%22 cols=%2260%22 id=%22ta%22></textarea><br><a href=%22http://%22 onclick=%22ta=document.getElementById('ta'); ta.value = ta.value.replace(/\n|\t/g, ' ').replace(/ +/g, ' '); return false;%22>Replace newlines and tabs</a>'; —-
Variable Scope Avoidance
A potential problem introduced by bookmarklets is that of namespace collisions: what if your bookmarklet uses or redefines a variable that is already in use by other scripts on the page? One technique to avoid this is to use random variable names that are unlikely to already be in use, but this can make bookmarklet code even more difficult to read and adds unnecessary length to the bookmarklet. A better solution is to create the bookmarklet as an anonymous function with its own variable scope. Here’s how this works:
javascript:(function() {  
  /* Bookmarklet code here - declare variables with 'var' before use */  
The function() { } part of this is an anonymous function — a function that does not have a name declared for it. By wrapping the function in parenthesis and adding () at the end the function is executed once as soon as it has been created, i.e. the instant the bookmarklet is activated. As long as variables within the anonymous function body are declared using the ‘var’ keyword, they will be constrained to the scope of the function and will not interfere with variables with the same name in the rest of the document. Thanks to JavaScript’s functional nature, you can even declare other functions within the anonymous function without adding them to the document’s global scope.
Appending Longer Scripts
I mentioned earlier that a method exists for bypassing Internet Explorer’s limit on the length of bookmarks. This method also allows bookmarklets to be written in standard indented JavaScript without needing to keep the whole script on a single line, making it a useful technique for more complicated bookmarklets implemented for any browser. The trick is to host the actual bookmarklet implementation as an external .js file on a Web server somewhere. The bookmarklet then just needs to contain “stub” code that loads in the rest of the script — a task that’s achieved easily within the 508 character limit. Here’s the loading stub bookmarklet code, indented for readability:
javascript:(function() {  
  var s = document.createElement('script');  
  s.setAttribute('src', 'http://url-of-main-bookmarklet-script');  
  s.setAttribute('type', 'text/javascript');  
With whitespace removed, the above code (minus the external script URL) comes to 193 characters. This code has one drawback: it doesn’t work with IE5 for the Macintosh. If IE5 Mac support is important for your bookmarklet, liorean has an extended version of the loading stub that uses browser detection to cater for that browser as well.
Further Reading
The best way to learn about bookmarklets is to look at those written by others: I hope that this whirlwind tour of bookmarklets has inspired you to try your hand at creating your own.

Frequently Asked Questions about Bookmarklets

What are bookmarklets and how do they work?

Bookmarklets are small pieces of JavaScript code that are stored as a URL within a bookmark in your web browser. When you click on the bookmark, the JavaScript code runs on the current page instead of loading a new page. This allows you to add new features to a website, automate repetitive tasks, or even play games, all without needing to install any software or extensions.

How do I create a bookmarklet?

Creating a bookmarklet is as simple as creating a bookmark. Instead of entering a URL, you enter a piece of JavaScript code. This code will be executed when you click on the bookmark. You can write your own code or find pre-made bookmarklets online.

Are bookmarklets safe to use?

Bookmarklets are generally safe to use, as they run in your browser and do not have access to your computer’s file system. However, like any code, they can be used maliciously. Always make sure to only use bookmarklets from trusted sources and understand what the code does before using it.

Can I use bookmarklets on any website?

In theory, bookmarklets can be used on any website. However, some websites may have security measures in place that prevent bookmarklets from working. Additionally, the functionality of a bookmarklet may depend on the structure of the website it is used on.

Why are my bookmarklets not working?

There could be several reasons why your bookmarklets are not working. The website you are trying to use them on may have security measures in place that prevent bookmarklets from working. The code in the bookmarklet may be outdated or incompatible with the website. Or there may be an error in the code itself.

How can I debug a bookmarklet?

Debugging a bookmarklet can be a bit tricky, as they do not have a traditional debugging environment. However, you can use the browser’s developer tools to inspect the code and see any error messages. You can also try running the code in the browser’s console to see if it works there.

Can I use bookmarklets on mobile devices?

Yes, you can use bookmarklets on mobile devices. However, the process of adding and using them can be a bit more complicated than on a desktop browser. You may need to manually enter the JavaScript code into a bookmark, as mobile browsers often do not support the drag-and-drop method used on desktop browsers.

Can I share bookmarklets with others?

Yes, you can share bookmarklets with others. Simply send them the JavaScript code and instructions on how to add it to their bookmarks. However, remember to only share bookmarklets from trusted sources and that you understand what the code does.

Can I use bookmarklets to change the look of a website?

Yes, you can use bookmarklets to change the look of a website. This is done by manipulating the website’s CSS. However, these changes are only temporary and will be lost when you refresh the page.

Can I use bookmarklets to automate tasks on a website?

Yes, you can use bookmarklets to automate tasks on a website. This can be anything from filling out forms to clicking buttons. However, the functionality of the bookmarklet will depend on the structure of the website and the task you want to automate.

Simon WillisonSimon Willison
View Author
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form