0

I have a JavaScript bookmarklet that is working fine in Chrome (v21) and Safari (v6) but when I try to use it in Firefox (v14) or IE (v9) and I get a page that just says:

[object HTMLScriptElement]

The bookmarklet is this (all the PHP statement at the end inserts the API key):

javascript: (function(src, cb) {
var s = document.createElement('script');
s.charset = 'UTF-8';
document.body.insertBefore(s, document.body.firstChild);
s.src = src;
if (typeof cb === 'function') {
    s.onload = cb;
    s.onreadystatechange = function() {
        (/loaded|complete/).test(s.readyState) && cb(s);
    };
}
return s;
}('http://towatchlist.com/marks/bookmarklet2response?uid=<?php echo $userID; ?>'))​

I don't think it's even loading the bookmarklet at all. In Firefox the URL bar changes to be the code above; in IE it doesn't even change from whatever page it's on.

I did try wrapping the bookmarklet in a self-executing function expression as suggested elsewhere, but that just resulted in Uncaught SyntaxError: Unexpected token ( in the Chrome console (and nothing else). Here's how I wrapped it:

javascript: (function() {
function(src, cb) {
    var s = document.createElement('script');
    s.charset = 'UTF-8';
    document.body.insertBefore(s, document.body.firstChild);
    s.src = src;
    if (typeof cb === 'function') {
        s.onload = cb;
        s.onreadystatechange = function() {
            (/loaded|complete/).test(s.readyState) && cb(s);
        };
    }
    return s;
}('http://towatchlist.com/marks/bookmarklet2response?uid=<?php echo $userID; ?>')
}());​

Perhaps I didn't wrap it quite right? In any case, what do I need to change in order to make IE/Firefox actually execute the bookmark?

Community
  • 1
  • 1
Nick
  • 3,172
  • 3
  • 37
  • 49

1 Answers1

2

A bookmarklet must not return anything. Just remove the return s; line and you should be good.

More generally, you can wrap the whole thing (or more accurately the last statement) in a void() function call to ensure that there is no return value.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thanks, taking out the return line was all that I needed. – Nick Aug 09 '12 at 00:30
  • There is no need for a `void` when the code is already wrapped in a immediately invoked function expression (aka self executing anonymous function). I've never seen that used together with the `void` technique and doing so would probably seems a bit odd and redundant. Simply removing the `return` was all that was necessary. – DG. Aug 09 '12 at 04:08