切勿使用.onload
, .onclick
等来自用户脚本。(这在常规网页中也是不好的做法)。
原因是用户脚本在沙箱中运行(《孤立的世界》),并且您无法在 Chrome 用户脚本或内容脚本中设置或使用页面范围的 javascript 对象。
总是使用addEventListener()
(或等效的库函数,如 jQuery.on()
)。另外,你应该设置load
添加之前的监听者<script>
DOM 节点。
最后,如果您希望访问页面范围内的变量(A
在这种情况下),你必须注入代码确实如此。 (或者你可以切换到 Tampermonkey 并使用unsafeWindow
, but 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.
}
... ...