繁体   English   中英

为什么script.onload无法在Chrome用户手册中使用?

[英]Why is script.onload not working in a Chrome 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使用.onload.onclick等。 (这在常规网页中也很糟糕)。

原因是用户脚本在沙箱中运行( “孤立的世界” ),并且您无法在Chrome用户脚本或内容脚本中设置或使用页面范围的JavaScript对象。

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

最后,如果您希望访问页面范围中的变量(在本例中为A ),则必须注入执行此操作的代码 (或者您可以切换到Tampermonkey并使用unsafeWindow ,但Chrome 27会导致问题 。)

使用类似的东西:

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

... ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM