Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 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);
    }elseif(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/.

Post a Comment for "Make A Bookmarklet Execute A Function That It Downloads"