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?

Upvotes: 1

Views: 1915

Answers (2)

The following works as desired on IE 10.0,9, Firefox 28, and Chrome 35.0.1916.114:

javascript:(function () {
    new_script = document.createElement("script");
    new_script.setAttribute('src','http://www.mydomain.com/myscript.js');
    if(new_script.addEventListener) {
        new_script.addEventListener("load", function() { do_stuff('Hello World!'); }, false);
    }else if(new_script.readyState) {
        new_script.onreadystatechange = function() { do_stuff('Hello World!'); };
    }else {
        new_script.onload = function() { do_stuff('Hello World!'); };
    }
    document.body.appendChild(new_script);
})();

I added the first 2 "if" blocks per the suggestions made here: http://msdn.microsoft.com/en-us/library/ie/hh180173%28v=vs.85%29.aspx. That was incomplete as Firefox balked without the final block. Note that "do_stuff" must be wrapped in an anonymous function. Otherwise, IE says it does not know what "do_stuff" is. I have not yet tested Opera and Safari. For those interested in some elaboration on DG's answer, this link provided by Matthew Lock was also a helpful reference: http://secretdiaryofhan.wordpress.com/2008/02/02/including-remote-javascript-in-a-bookmarklet/.

Upvotes: 1

DG.
DG.

Reputation: 3517

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.

Upvotes: 2

Related Questions