7

,有一個頁面http://example.com/1.php包括JavaScript文件和往常一樣:window.onload適用於Firefox + Greasemonkey腳本,但不適用於Chrome用戶腳本?

<script type="text/javascript" src="/util.js?1354729400"></script> 

此文件包含名爲exampleFunction,我需要在我的userscript使用功能。 我也有一個用戶腳本:

// ==UserScript== 
// @name   SomeName 
// @namespace  http://example.com/userscripts 
// @description Greets the world 
// @include  http://example.com/* 
// ==/UserScript== 
window.onload = function() { 
     console.log(exampleFunction); 
     alert("LOADED!"); 
} 

這完美的作品在Firefox,並返回在Chrome中的錯誤:

Uncaught ReferenceError: exampleFunction is not defined 

我如何工作的呢?

+0

嘗試禁用緩存在Chrome或按CTRL + F5 – Ibu

+0

它沒有幫助 – Alex

回答

9

exampleFunction未定義的原因是Chrome用戶腳本在沙箱中運行("isolated world")。需要注意的是Greasemonkey腳本經常在沙箱中運行過,但你是目前an implicit @grant none運行。
如果你的腳本是使用GM_功能,它將停止在Firefox工作壓力太大。

要使這個腳本在兩個瀏覽器(以及其他一些瀏覽器)上都能正常工作,請使用腳本注入similar to this answer

但是,還有另一個問題,因爲該腳本使用window.onloadChrome userscripts, with the default execution start-mode, will often never see the onload event.

要解決這個問題,添加// @run-at document-end元數據塊。

所以腳本變爲:

// ==UserScript== 
// @name   SomeName 
// @namespace  http://example.com/userscripts 
// @description  Greets the world 
// @include   http://example.com/* 
// @run-at   document-end 
// @grant   none 
// ==/UserScript== 

function GM_main() { 
    window.onload = function() { 
     console.log(exampleFunction); 
     alert("LOADED!"); 
    } 
} 

addJS_Node (null, null, GM_main); 

//-- This is a standard-ish utility 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); 
} 
+0

它並不總是工作......我無法確定 – Alex

+1

的** **如何被它「不工作」的原因是什麼? ***完全***的症狀是什麼?使用答案中的腳本,不加改動,而是用「@ include」這一行。 **網頁的網址是什麼**腳本顯示不起作用?該頁面是否需要很長時間才能完全加載?直到最後一個大圖像等完成下載後,「onload」纔會啓動。 –

+0

親自試一試:刪除「console.log(exampleFunction);」並從腳本中留下「警報」。留在這個頁面上,點擊你的個人資料鏈接,並多次刷新該頁面。它是如何爲你工作的?我在一半的情況下都沒有得到onload事件 – Alex

1

你有沒有打過電話用括號examplefunction? :) 像這樣:

console.log(exampleFunction()); 

如果您嘗試在Chrome控制檯,你必須加上括號調用函數。

+1

這不會做任何事情,如果exam​​pleFunction真的是不確定的。 – Stuart

1

如果你想在相當於onLoad,這不火,直到頁面上的所有圖像加載,你想在你的元數據塊使用// @run-at document-idle。默認的document-end在加載DOM時觸發,相當於document.ready。

相關問題