2013-05-29 67 views
4

我想使用腳本在站點中加載另一個腳本文件。 但是,js.onload事件無法正常工作。爲什麼script.onload在Chrome用戶腳本中不起作用?

的userscript文件:

// ==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' 
} 


在鉻,控制檯輸出 「未定義」,但load.js已經完全加載。

我在Firefox中測試過它,並且它正確輸出A

+0

注意,它只能在FF + Greasemonkey的工作因爲'@ grant'默認爲'none'。只要您嘗試使用任何'GM_' API函數,腳本就會在FF上破壞。 –

回答

6

從不使用.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. 
} 

... ... 
+0

非常完美,非常感謝! – chunterg

+0

不客氣;樂意效勞! –

+0

@BrockAdams 'scriptNode.addEventListener(「load」,runOnLoad,false);'這裏的錯誤是什麼? –

相關問題