Hack 35. Create Large, Maintainable Bookmarklets


Create easy-to-maintain bookmarklets of arbitrary size.

A bookmarklet is a special piece of JavaScript code that can be dragged into a user's Links toolbar and later clicked on to implement cross-site behavior. Bookmarklets have size limitations, which differ based on browser and platform, since they must fit into a certain number of characters. They can also be difficult to maintain for more sophisticated scripts, since every line of JavaScript code has to be jammed into one line.

This hack presents a mechanism to create arbitrarily sized bookmarklets, where most of the code resides outside of the bookmarklet link. It has been tested in IE 6 and Firefox.

Bookmarklet Code

Let's begin by viewing the full bookmarklet source code:

<p>Drag the following link to your toolbar to  install this bookmarklet:</p> <a href= "javascript:function loadScript(scriptURL) { var scriptElem =  document.createElement('SCRIPT'); scriptElem.setAttribute('language',  'JavaScript'); scriptElem.setAttribute( 'src', scriptURL); document.body.appendChild(scriptElem); }  loadScript('helloworld.js');">Say Hello World</a>

The essential idea in this code is that we dynamically insert a new script element into the DOM through our bookmarklet. Here is the code within the bookmarklet URL, formatted to be more readable:

function loadScript(scriptURL) {     var scriptElem = document.createElement('SCRIPT');     scriptElem.setAttribute('language', 'JavaScript');     scriptElem.setAttribute('src', scriptURL);     document.body.appendChild(scriptElem); } loadScript('http://216.203.40.101/projects/tutorials/'            + 'creating_huge_bookmarklets/helloworld.js');

The previous code sample created a new script element and set it to the new URL. We then append the new script block to the document. The script we append, helloworld.js, is very simple:

alert("Hello World!");

When this script is loaded, the "Hello World!" message appears immediately.

The loadScript( ) function definition and function call are rolled into a single JavaScript URL to turn it into a bookmarklet.

You can enter the script yourself by dragging the link to your toolbar. Then navigate to another site and click the bookmarklet link. You will see the message "Hello World!" appear, loaded from an external script.

The external script loaded through the bookmarklet can come from a different domain than the web site itself, opening the door to sophisticated bookmarklets that aggregate data from different web sites. See http://www.bookmarklets.com for some of the interesting work people have done with bookmarklets.

Brad Neuberg




Ajax Hacks
Ajax Hacks: Tips & Tools for Creating Responsive Web Sites
ISBN: 0596101694
EAN: 2147483647
Year: 2006
Pages: 138

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net