Why is script.onload not working in a Chrome userscript?

血红的双手。 提交于 2019-12-01 05:54:29
Brock Adams

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

... ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!