Search code examples
javascriptbookmarklet

Make A Bookmarklet Execute A Function That It Downloads


I would like to create a bookmarklet that downloads a remote javascript file in which a function is defined and then executes that function with parameters that are hard-coded into the bookmarklet.

Here is your standard "download-and-run-remote-script" bookmarklet with an extra function call in the last line:

javascript:( function () { 
    var new_script = document.createElement("script"); 
    new_script.src = "http://mydomain.com/myscript.js"; 
    document.body.appendChild(new_script);
    do_stuff('Hello World!');
} ) ();

Here are the contents of myscript.js:

function do_stuff(input_variable) {
    alert(input_variable);
}

As written, this doesn't do anything. Why not? What should I do differently?


Solution

  • Scripts load asynchronously. That means that the script doesn't finish loading before you try to run the function.

    Solution 1.) myvar = 'Hello World!' in bookmarklet and do_stuff(myvar) in myscript.js.

    Solution 2.) Use the onload event for the script element you create. More robust, but more complicated.