Javascript 为什么script.onload在Chrome用户脚本中不起作用?

Javascript 为什么script.onload在Chrome用户脚本中不起作用?,javascript,google-chrome,userscripts,script-tag,Javascript,Google Chrome,Userscripts,Script Tag,我想使用userscript在站点中加载另一个脚本文件。 但是,js.onload事件不能正常工作 用户脚本文件: // ==UserScript== // @name Code highlight // @description Test // @include http://localhost/* // @version 1.0 // ==/UserScript== var js = document.createElement('sc

我想使用userscript在站点中加载另一个脚本文件。 但是,
js.onload
事件不能正常工作

用户脚本文件:

// ==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)
    }
load.js文件:

var A = {
    name:'aa'
}

在Chrome中,控制台输出“undefined”,但load.js已完全加载


我在Firefox中测试了它,它正确地输出了
A

永远不要从用户脚本中使用
.onload
.onclick
,等等。
(在普通网页中也是一个糟糕的做法)

原因是userscripts在沙盒()中运行,您不能在Chrome userscript或内容脚本中设置或使用页面范围javascript对象

始终使用
addEventListener()
(或等效的库函数,如jQuery
.on()
)。另外,在将
节点添加到DOM之前,应该设置
加载
侦听器

最后,如果您希望访问页面范围中的变量(本例中为
A
),则必须这样做。(或者您可以切换到Tampermonkey并使用
unsafeWindow
,但是。)

使用类似于:

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);
}

或许:

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

... ...

请注意,它仅在FF+Greasemonkey中工作,因为
@grant
默认为
none
。只要您尝试使用任何
GM
API函数,脚本也会在FF时中断。@BrockAdams
scriptNode.addEventListener(“load”,runOnLoad,false)此处为假是为了什么?@viditjain,请参阅。在这种情况下,添加显式的
,false
是一种编码样式选择。