Bookmarklet : Adding functions to pages
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 (which is now replaced by Firefox).
Format of a bookmarklet
The code is placed between single quotes, which allows to integrate double quotes in instructions. We can do the opposite.
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:
- Change the look of a page. Colors, fonts ...
- Get information on the page. For example the number of links, as shown in the demo.
- Access to sites while passing parameters to them.
For that a dialog box is opened (prompt command), the result of which is assigned to a variable, which is passed in the URL of the site.
- Add on its website buttons to social sites like Digg, Delicious, so visitors can vote for the article.
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.
Some examples of what can be done with bookmarklets.
This simple bookmarklet displays a message.
How many links in this page?
Display the number of <a> tags in the current page.
Changing the color of the page
Use the format #xxxxxx
Accesses the search service from Google.
Validate the page
Give a URL to the W3C validator. The current page by default.