Monday, January 12, 2009

Are bookmarklets still cool?

I'm by no means an accomplished Javascript programmer, but I'm pretty good at writing small scripts and very lazy when I'm faced with repetitive tasks. So, when I wanted to rip a series of pictures off a website's page (and I had asked permission from the website's owner), I wrote a small Javascript bookmarklet to do it for me.

Just type cut and paste the following code into a bookmark, then click on the bookmark on whichever page has the pictures you want. It will leave you with a page full of image tags you can cut and past onto your own site, provided you got permission from the pictures' owner.

javascript:var htmlDiv = document.createElement('div');var garbageDiv = document.createElement('div');var pageImages = document.images;while (pageImages[0]) {var cleanImage = document.createElement('img');cleanImage.setAttribute('src', pageImages[0].src);htmlDiv.appendChild(cleanImage);garbageDiv.appendChild(pageImages[0]);} var body = document.getElementsByTagName('body')[0];body.style.backgroundColor = '#ffffff';body.innerHTML = '';void(body.appendChild(document.createTextNode(htmlDiv.innerHTML)));

It's a relatively ugly script, but it's easily understandable, nonetheless. It starts by initializing a couple variables: htmlDiv to store the pictures and garbageDiv to hold the pictures that have already been scanned. pageImages just saves me the trouble of typing in document.images over and over again. A simple while loop runs while there is something in the first slot of pageImages. Within the while loop, a new, blank img element called cleanImage is created, given the src of the current picture, and appended to htmlDiv. The current image is then appended to garbageDiv, thus removing it from the page and the pageImages array. Once the loop terminates, the whole page is restyled to have a white background (the website I made it for had a black background) and its contents are replaced by the HTML inside htmlDiv.

If you're wondering, that void() block at the end is necessary because bookmarklets are required to return something. If you didn't have that block there, the last line of code would return true and the only thing left on the screen would be true.

I have at least one more bookmarklet to show off when I again run out of things to say. It's a little more specialized, but it's useful, nonetheless.