Search code examples
javascriptbookmarklet

Defining multiple global functions in a JavaScript bookmarklet


I'm working on a bookmarklet, which needs several functions. Individually, I can define any function I need by calling something like:

javascript:void(window.test1=function(){alert('hi');});

But as soon as I try to add a second function, it stops working.

javascript:void(window.test1=function(){alert('hi');}window.test2=function(){alert('bye');});

Running this generates an error in the console saying "Unexpected identifier". I have tried separating the two function declarations with a semicolon, a space, and a carriage return (the latter two hex-encoded as %20 and %0A), inserting them between thus:

javascript:void(window.test1=function(){alert('hi');};window.test2=function(){alert('bye');});

This doesn't work either; it yields the error message "Unexpected token".

How do I define two functions consecutively in the context of a bookmarklet?


Solution

  • Try wrapping all inner function in 1 function and define all needed function in inner function as properties/methods on window object as you are doing here.

    Thus:

    javascript:void(function(){window.test1=function(){alert('hi');};window.test2=function(){alert('bye');}}());