Thursday, August 6, 2009

iPhone Bookmarklet Installer Source

iPhone BookmarkletsA few hours ago, I posted my iPhone Bookmarklet Installer Bookmarklet and several people have asked how it works.

Well, it's pretty basic. The effort is to loop through all the links on the page, identify the bookmarklets, and modify them so that the bookmarklet is appended to the URL somehow. The first time I tried, I used the '?' character making the bookmarklet look like a query string. This proved problematic though as a number of bookmarklets failed to convert cleanly. I didn't really investigate but I'd imagine it has something to do with the '&' character and/or '=' signs.

In any event, it's pretty easy to fix that by using the '#' character instead of ? because then it just looks like an anchor. It also keeps the page from having to reload. So, all you have to do is run the bookmarklet on your iPhone, click the bookmarklet you want to install, save the bookmark and remove everything up to and including the #.

Now, the actual bookmarklet code has been scrubbed a little to give it something of a smaller footprint like this:
var s,i,l=document.links;


But, that's a little hard to read, so here's the pre-scrubbed version. There's also an additional section I added later to make it easier to identify which links have been transformed (i.e., which are identified as bookmarklets). Here's the code:
// anonymous function

// put the link array somewhere
var links = document.links;

// loop through all the links
for (var i = 0; i < links.length; i++)

// if the link does not start with javascript:
// it isn't a bookmarklet and we can exit this
// itteration and continue the loop
if(links[i].href.indexOf('javascript:') != 0)

// update the href of the link prepending the
// '#' character to make it look like an anchor
links[i].href = '#' + links[i].href;

// add some styling information to identify the
// modified links
var style = links[i].style;
style.backgroundColor = '#eee';
style.color = '#333';
style.border = '1px solid #333';
style.textDecoration = 'none';
style.padding = '2px';
style.fontWeight = 'normal';

1 comment: