Tommy Chheng

Icon

All Things Programming!

How to make a Javascript Bookmarklet

There’s a niffy trick in browsers that you you execute Javascript code in the url location bar. (This is how a lot of security holes are created too!)
Try typing the below into your browser url bar:

javascript:alert('look how cool this is')

Cool, it runs javascript!

You may have noticed a lot of websites take advantage of this to enhance a service. Instapaper’s “Read Later” saves the current page and Pastefire’s “Pastefire this” saves the selected text.

To make your own, just write javascript inside a link tag as a one liner. Then just ask users to click and drag the link to the bookmark toolbar.

Here’s an example for my Next Sprocket site which will start you on a new open source task with the title and description partially filled out:
Sprocket it!


<a href="javascript:(function(){location.href='http://nextsprocket.com/tasks/new?task[title]='+encodeURIComponent(document.title)+'&task[description]=More details at '+encodeURIComponent(window.location.href)})()">Sprocket it!</a>

Category: Programming

Tagged:

blog comments powered by Disqus

Read Books on the Amazon Kindle 3