Bookmarklet : Adding functions to pages

A bookmarklet - or favelet - is a link that contains JavaScript code assigned to the href attribute. The interest is to incorporate functions to a Web page throught a link to click, to the execution of a script.
But it is most often incorporated into bookmarks - hence its name - to add functionalities to the browser.
The examples in the demonstration page will show what we can do with bookmarklets.

Bookmarklets exist in the Netscape browser since 1995 is now replaced by Firefox.

Format of a bookmarklet

The keyword javascript introduce code in the attribute of an HTML tag, as follows:

<a href='javascript:alert("hello");'> My function </ a> 

The code is placed between single quotes, which allows to integrate double quotes in instructions. We can do the opposite.
Everything that follows javascript: within a string is processed by the browser as code.

The code may consist of several instructions and be fairly complex provided it is composed of a single line. It has access to the DOM tree of the page and on all the elements of it.

Examples of applications

You can add features to:

Reminder about the prompt command

It opens a dialog box with a text input field and returns the text typed by the user, or false if nothing is entered.

The interface of the function has two parameters:
- The label shown in the box.
- A default value for the text input field.

var x = prompt ( "Enter something:", "default"); 

You can use the variable as follows:

location.href = 'https://www.xul.fr?uri =' + escape (x) 

location.href loads another page.
A parameter is passed with the ? symbol (See Sending parameters to a web page, the escape function converts the text for a valid URL format.

Bookmarklets demonstrations

Some examples of what can be done with bookmarklets.


Bookmarklet link
This simple bookmarklet displays a message.

javascript:alert("You have just clicked on a bookmarklet.");

How many links in this page?
Display the number of <a> tags in the current page.

javascript:alert("Number of link in this page: " + document.links.length);

Changing the color of the page
Use the format #xxxxxx

javascript:void(document.body.bgColor=
prompt("Background color for this page:", "#F3F3F3"));

Google search
Accesses the search service from Google.

javascript:void(x=prompt("Search...","bookmarklet"));
if(x)location.href="http://google.com/search?query="+escape(x)+"&amp;num=10"

Validate the page
Give a URL to the W3C validator. The current page by default.

javascript:void(x=prompt('URL à vérifier...',document.location));
if(x)location.href='http://validator.w3.org/check?uri='+escape(x)

See also

© 2008-2012 Xul.fr