« - »

Adding an Icon to Your Bookmarklet

16 July 2010

The other day I needed to create a bookmarklet, which was an interesting exercise in and of itself, but once I got all of those issues worked out, I wanted to make it pretty by adding an icon. Apparently, this is not something easily accomplished, and there is little information out there that I could locate on how one might go about doing this. I did manage to find this, though, over at tapper[ware]:

Offering Bookmarklets with icons

Now, I have to say that his little hack to make all of this magic happen is rather ingenious, and I do like it. I just could not get it to work in my version of Firefox. Everything started out great in the beginning. The first example worked just fine for me. I can take this little icon:

… and add it to this bookmarklet:

Click Me!

…. and the image shows up just as advertised. Drag it up to your browser’s tool bar and see for yourself. It works! But when I started getting into the conditional stuff, the icon would only show up when the HTML side was true, not when the Javascript side was true. In other words, I could have my choice of a working bookmarklet with no icon or a bookmarklet with a nice icon that didn’t do anything! I could never figure out how to get it to recognize the HTML side of the conditional and load the icon, yet execute the Javascript when the bookmarklet was clicked. I could get one to work, or I could get the other to work, but I could never get them both to work at the same time.

Apparently, I’m just not smart enough to figure that out, so I did the next best thing and just gave up trying, and then went with a slightly different approach:

Click Me!

This version uses the window.location.href as it’s conditional, so if you are on the page that hosts the bookmarklet you get the HTML, otherwise you get the Javascript. Now, using this approach, the bookmarklet doesn’t function on the page on which you got it, but when you are on that page, you can load the icon, and once loaded, it’s there for life. Here’s what it looks like under the hood:

<a href="javascript:if(window.location.href.indexOf('http://blog.restafarian.org/')==0)
alert('Do%20bookmarklet%20stuff%20...');}">Click Me!</a>

There’s probably a better way to do this still, but I did what I could to do what I wanted to do, and that’s going to have to be good enough for now!


Leave a reply

You must be logged in to post a comment.