15 April 2007

Background Bookmarklets

To summarize for the sake of brevity: [How can I load a page with a browser bookmarklet without actually viewing the page?]Dave

First, to provide a little background, Dave wanted to save bookmarks to a server on the Internet (like del.icio.us) but at a location under his control. More importantly, leaving the current page to do so (like del.icio.us) was unnecessary and unwanted.

So, how do we do that? If you said AJAX like I did at first, your wrong! The XMLHTTPRequest object Ajax uses won't operate across domains for security reasons. So, what is the solution then? We need to use JavaScript to ensure a one-click affair, but the champion of JavaScript and Web 2.0 has left us out in the cold. We must use the old stand by of JavaScript and DHTML, the Image object.

The Image object provides some very useful behavior for us.

  • Unless you are crossing the HTTPS boundary, there aren't really any security mechanisms around by default to get in our way.

  • We can create an manipulate Image objects without every displaying them, or anything else, to the user.

  • Image objects are fairly cheap to create an use, unlike trying to fire up ActiveX, Java, or Flash.

  • Image objects will load any arbitrary URL we give them immediately and in the background, providing us with flexible, asynchronous behavior.



So, here is the code.

var img = new Image();
img.src = "http://localhost/bookmark/";


But wait! Where is the URL we want to bookmark? Easy, its in the referrer header sent to the target web server. If you don't want to trust referrers, all you need to do is escape and use the location.href property.

var img = new Image();
img.src = "http://localhost/bookmark/" + escape(location.href);


Now, there are a few things you can do with this. Start the entire thing off with javascript: and you've got a suitable bookmarklet. Wrap that in a tags and you have a click-able link you can embed in pages.

If you are interested, here is the mailing list thread this was discussed in.

No comments: