Firefox Bookmarklet: Exposing functions to the global namespace

I’m working on a moderately-complex Bookmarklet that works just fine in Chrome, but I can’t get it to work in Firefox. When I run my Bookmarklet in Firefox it redirects to a new page that only says true on it.

I’ve narrowed the cause down to a very specific thing: Firefox doesn’t seem to like when you expose new functions to the global namespace.

  • How a bookmarklet can avoid the popup blocker
  • Change url with bookmarklet
  • What does tstbklt() from the Tumblr bookmarklet javascript do?
  • Creating thumbnail squares of images in javascript (without losing aspect ratio)
  • Find and replace in a webpage using javascript
  • Combining two bookmarklets
  • If this is the case, might you know more about it? Is this documented anywhere, such that I can learn more about it? Resources on the nuances of bookmarklet-building seem scarce, and I can’t find anything relevant. A second question would be if there are there any known workarounds.

    And for some examples (remember, to test them simply copy these lines of code into a bookmarklet in Firefox. Then run them on any page).

    Redirecting bookmarklets

    javascript:!function(){window.okay={test:function(){}}}();

    The project I’m working on

    A Non-redirecting bookmarklet

    javascript:!function(){window.okay={test:!0}}();

    Any thoughts? Thanks!

    For now, I plan to use manual subscriptions in Knockout to get the functionality I need. It’d still be nice to know the answer to this question, though.

  • Differences between two regex JavaScript bookmarklets
  • Creating Bookmarklet: Append current URL with specific string
  • Create a favicon for a link that is JavaScript?
  • GWT bookmarket or GWT as an external library
  • Does execCommand SaveAs work in Firefox?
  • Is there a way to automatically convert a Greasemonkey script into a bookmarklet?
  • One Solution collect form web for “Firefox Bookmarklet: Exposing functions to the global namespace”

    It has nothing to do with exposing globals. It has everything to do with the final evaluated value of your bookmarklet.

    Any JS code that is evaluated always returns a value which comes from the last line of code or the last block.

    For me, in Firefox, both of your examples redirect because both return true. You can test this by pasting the code directly into Firefox console.

    Furthermore…

    javascript:!function(){...}();
    

    This is weird. I’ve never seen this pattern.

    This is the most common bookmarklet pattern these days:

    javascript:(function(){...})();
    

    As long as you don’t end that anonymous function with a return, that pattern evaluates to undefined, and no redirect happens.

    The older way of achieving the same result was to always use void(0); as the last line of code. That evaluates to undefined also, and if it is the last line, then the entire script evaluates to undefined, and no redirect happens.