Monday, August 08, 2005

Bookmarklets (part 2)

How it works

If you take a look at the source code for the above you'll notice that all of the scripts begin with javascript:. This tells the browser to interpt the rest of the URL as a script (yes, that means you could just as well type the script in the address by with 'javascript:' in front.)

Next, you'll see that most of the scripts have several statements enclosed with curly brackets, '{' & '}'. These signify a code block that has been used in place of a single statement. I'm not sure how REQUIRED they are for use in bookmarklets, but its simply good programing form to use them if your script contains multiple statements. After the closing bracket, you'll see that most scripts also return a value with 'void(1);'. This ensures that your script returns a positive exit code, which may be required for some browsers to use your script properly.

Modern browsers support executing a wide range of JavaScript code from the address bar, and thus the bookmark bar. [Time] will display the current time in Safari.

The hardest part in turning a normal script written in JavaScript into a bookmarklet is formatting. The code must all appear on a single line, which is a great pain for anyone with any coding sense. What I pfer to do is write the script in another application, with normal formatting, and then take out all the extra whitespace.

This also means removing all the spaces. In most cases, you can just run statements together, but where the space character is required (ie “else if” conditionals) you must encode the space with the %20 escape sequence.

This allows the browser address bar to handle the space correctly. Its very important, so I'll say it again, “YOU MUST ESCAPE SPACES IN YOUR CODE BY USING %20”.

That about wraps it up for the basics. A lil JavaScript knowledge, and you'll be dangerous writing bookmarklets in no time.

If you write/find any cool scripts, post them below in the comments. To insert a link like the ones above, simply use this format:

<a href=“javascript:{CODE HERE};void(1);”>Script Title</a>


There are security issues involved any time you run scripts on your computer. Make sure you've checked the source code & know exactly what you're executing when you click that bookmark. Or, get the bookmarklets from a trusted source. If you've found a script, but aren't sure if it's safe, feel free to post it here, using the same method as above. Put a note in your comment that you'd like me to check it out for you. I'll reply with what I find out.

Happy Scripting


Post a Comment

Links to this post:

Create a Link

<< Home