Question

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.

Was it helpful?

Solution

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.
}

... ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top