JavaScript Tutorials Beginner
AJAX: Creating Huge Bookmarklets
A bookmarklet is a special piece of JavaScript code that can be dragged into a user's link toolbar, and which later can be clicked on to implement cross-site behavior. People have done all sorts of cool stuff with it.
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.
I've put together a way to have huge, arbitrarily sized bookmarklets, where most of the code resides outside of the bookmarklet link. I'll explain how this works in this mini-tutorial.
Here is the entire code:
<html>
<body>
<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('http://www.javascriptsearch.com/documents/helloworld.js');
">Say Hello World</a>
</body>
</html>
The essential idea is that we dynamically insert a new script element into the DOM through our bookmarklet. Here is the code that is 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://http:www.javascriptsearch.com/' + '/documents/helloworld.js');
In the code above we create a new script element and set it to the new URL. We then call the script with a URL that is different than the Coding in Paradise site, to show that cross site scripting insertion works. We then append the new script block to the document. The script we use, helloworld.js, is very simple:
alert("Hello World!");
When this script is loaded, it will immediately cause the Hello World message to appear.
The full loadScript method and method call are rolled into a single javascript: URL to turn it into a bookmarklet.
Try the script yourself, dragging the link to your toolbar. Then, navigate to other sites and click the bookmarklet link; you will see the message Hello World appear, loaded from an external script.
This code has been tested in IE 6+ and Firefox.
—
JavaScripts Guides: Beginner, Advanced
JavaScripts Tutorials: Beginner, Advanced
[Home] [Templates] [Blog] [Forum] [Directory] JavaScript Tutorials Beginner -
AJAX: Creating Huge Bookmarklets
|