0

I want to add a script to a given page with a Greasemonkey style user script in Chrome.

I use this trick to add jQuery to my user script.

If I try to add i.e. <h1>Test</h1> to a pages body with jQuery's append-method, everything works fine.

However if I try to append a JS-script nothing happens.

How do I troubleshoot a problem like this?

This is my .user.js-file:

// ==UserScript==
// @match http://*/*
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

// the guts of this userscript
function main() {

$(document).ready(function() {
    $('body').append('<script type="text/javascript" src="http://timkl.com/wip/bibobRedesign/js/jquery.contenthack.js"></script>');
});

}

// load jQuery and execute the main function
addJQuery(main);
timkl
  • 3,299
  • 12
  • 57
  • 71

1 Answers1

2

jQuery handles script elements differently than other DOM elements. There is additional detail in this answer.

To append your script the safest way would be to use the same method that is used to insert the jQuery library.

function main() {
    var script = document.createElement("script");
    script.setAttribute("src", "http://timkl.com/wip/bibobRedesign/js/jquery.contenthack.js");
    document.body.appendChild(script);
    $(document).ready(function () {
        //$('body').append();
    });
}

Untested Option
If you have lots of scripts to load take a look at a script loader (such as LABjs)

You might be able to do something like the following:

function addLABjs(callback) {
    var script = document.createElement("script");
    script.setAttribute("src", "http://somepath.to/LAB.js");
    script.addEventListener('load', function () {
        var script = document.createElement("script");
        script.textContent = "(" + callback.toString() + ")();";
        document.body.appendChild(script);
    }, false);
    document.body.appendChild(script);
}

// the guts of this userscript


function main() {
    $LAB.script("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js").wait()
        .script("http://timkl.com/wip/bibobRedesign/js/jquery.contenthack.js")
        .script("YourOtherScript.js").wait();

    $(document).ready(function () {
    });
}

addLABjs(main);
Community
  • 1
  • 1
Mark Coleman
  • 40,542
  • 9
  • 81
  • 101