從不使用.onload
,.onclick
等等。(這在常規網頁中也是不好的做法)。
原因是userscripts在沙箱中運行("isolated world"),並且您無法在Chrome用戶腳本或內容腳本中設置或使用頁面範圍的JavaScript對象。
始終使用addEventListener()
(或等效庫函數,如jQuery .on()
)。此外,您應該在將<script>
節點添加到DOM之前設置load
聽衆。
最後,如果您希望訪問頁面範圍中的變量(在這種情況下爲A
),則必須使用inject the code這樣做。 (或者你可以切換到Tampermonkey和使用unsafeWindow
,但Chrome 27 is causing problems with that。)
使用類似:
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上破壞。 –