chu*_*erg 5 javascript google-chrome script-tag userscripts
我想使用用户脚本在站点中加载另一个脚本文件.但是,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)
}
Run Code Online (Sandbox Code Playgroud)
load.js文件:
var A = {
name:'aa'
}
Run Code Online (Sandbox Code Playgroud)
在Chrome中,控制台输出"undefined",但load.js已完全加载.
我在Firefox中进行了测试,输出A正确.
切勿使用.onload,.onclick等从userscript. (这在常规网页中也很糟糕).
原因是用户脚本在沙箱中运行("孤立的世界"),并且您无法在Chrome用户脚本或内容脚本中设置或使用页面范围的JavaScript对象.
始终使用addEventListener()(或等效的库函数,如jQuery .on()).此外,您应该load在将<script>节点添加到DOM 之前设置侦听器.
最后,如果您希望访问页面范围中的变量(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);
}
Run Code Online (Sandbox Code Playgroud)
也许:
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.
}
... ...
Run Code Online (Sandbox Code Playgroud)