Simple bookmarklet not working in chrome
Yeah, you have an error in your code. I would like to show you how to find it yourself rather than just say where it is, so here goes a micro-tutorial ;)
Strip line comments (
//
) from your JS code as the bookmarklet will be on one line. You should end up with the code:var imgs = [];imgs = document.getElementsByTagName('img');var pictureurl = '';var linkurl = document.location.href;for(var i = 0; i < imgs.length; i++){ var str = imgs[i].getAttribute('id'); var find = str.search("myImage"); if(find != -1){ pictureurl = imgs[i].getAttribute('src'); alert('[URL=' + linkurl + '][IMG]' + pictureurl + '[/IMG][/URL]'); }}
Remove new line characters from the code and prefix the code with
javascript:
protocol so that Chrome knows that the contents is JavaScript code. Your code should now look like this:javascript: var imgs = []; imgs = document.getElementsByTagName('img'); var pictureurl = ''; var linkurl = document.location.href; for(var i = 0; i < imgs.length; i++){ var str = imgs[i].getAttribute('id'); var find = str.search("myImage"); if(find != -1){ pictureurl = imgs[i].getAttribute('src'); alert('[URL=' + linkurl + '][IMG]' + pictureurl + '[/IMG][/URL]'); } }
Create your bookmarklet as a bookmark and make sure its accessible (i.e. visible so you can click it in any Chrome window).
- Go to a page on which you will test your bookmarklet code.
- Open Developer tools by holding CTRL + SHIFT + I.
- Switch to the tab named Console.
- Click the bookmarklet.
- The console should now show you the errors/warnings that have been issued while executing the code of your bookmarlet.
In case of your code, it spits:
Uncaught TypeError: Cannot call method 'search' of null (program):1(anonymous function)
Which seems reasonable since search()
is invoked on the value of str
which contains a value of ID
attribute, but not all IMG
tags have an id
assigned.
What's cool is that you can click on the (program):1
on the right hand side of the window and debug the code, inspect variables, etc.