6

I want to load another script file, in a site, using a userscript. But, the js.onload event doesn't work correctly.

The userscript file:

// ==UserScript==
// @name           Code highlight
// @description    Test
// @include        http://localhost/*
// @version        1.0
// ==/UserScript==

var js = document.createElement('script');
    js.src = "http://localhost/test/js/load.js";
    document.getElementsByTagName("head")[0].appendChild(js);
    js.onload = function(){
        console.log(A)
    }

the load.js file:

var A = {
    name:'aa'
}


In Chrome, the console outputs "undefined", but the load.js has loaded completely.

I tested it in Firefox, and it outputs A correctly.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
chunterg
  • 128
  • 1
  • 1
  • 9
  • Note that it only worked in FF+Greasemonkey because the `@grant` was defaulting to `none`. As soon as you try to use any `GM_` API functions, the script would break on FF too. – Brock Adams May 29 '13 at 05:43

1 Answers1

11

Never use .onload, .onclick, etc. from a userscript. (It's also poor practice in a regular web page).

The reason is that userscripts operate in a sandbox ("isolated world"), and you cannot set or use page-scope javascript objects in a Chrome userscript or content-script.

Always use addEventListener() (or an equivalent library function, like jQuery .on()). Also, you should set load listeners before adding <script> nodes to the DOM.

Finally, if you wish to access variables in the page scope (A in this case), you must inject the code that does so. (Or you could switch to Tampermonkey and use unsafeWindow, but Chrome 27 is causing problems with that.)

Use something like:

addJS_Node (null, "http://localhost/test/js/load.js", null, fireAfterLoad);

function fireAfterLoad () {
    addJS_Node ("console.log (A);");
}

//-- addJS_Node is a standard(ish) function
function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}


Or perhaps:

addJS_Node (null, "http://localhost/test/js/load.js", null, fireAfterLoad);

function fireAfterLoad () {
    addJS_Node (null, null, myCodeThatUsesPageJS);
}

function myCodeThatUsesPageJS () {
    console.log (A);
    //--- PLUS WHATEVER, HERE.
}

... ...
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • @BrockAdams `scriptNode.addEventListener ("load", runOnLoad, false);` what is false here for? – vidit jain Jun 17 '15 at 12:28
  • @viditjain, See [the documentation](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). In this case, adding an explicit `, false` is a coding style choice. – Brock Adams Jun 17 '15 at 18:31