2011-01-27 92 views
4

不到十分鐘前,我決定編寫我的Greasemonkey的第一個腳本。我沒有經驗。另外,我的JavaScript有點生疏,因爲我上次寫代碼已經有一段時間了。但我不明白,爲什麼Greasemonkey的是給我這個錯誤:'文檔'在Greasemonkey中是未定義的

Line: 9 
Char: 2 
Error: 'document' is undefined 
Code: 800A1391 
Source: Microsoft JScript runtime error 

這裏是我的腳本:

// ==UserScript== 
// @name   Easier WatchSeries 
// @namespace  n/a 
// @include  http://www.watch-series.com/episode/* 
// ==/UserScript== 

function thing() 
{ 
    document.body.setAttribute('onload', show_links(document.getElementById('idepisod').value)); 
} 
thing(); 

所有我想要做的就是添加一個onload屬性body標籤。當我轉到「管理新用戶腳本」 - >「編輯」時,出現此錯誤。除此之外,腳本不做任何事情,所以顯然有些事情是錯的。

我正在運行Firefox 3.6.13。

回答

5

幾件事情:

  1. That cryptic error message has been found to happen when Greasemonkey does not have a proper editor set up

    1. 打開約:config在您的瀏覽器。
    2. 篩選器greasemonkey.editor
    3. 輸入一個有效的路徑到一個有效的編輯器。我喜歡TextPad,但c:\Windows\System32\notepad.exe應該可以在大多數Windows系統上工作。
    4. 可能需要重新啓動Firefox。

  2. 事件偵聽器可以不是這樣的添加由於Greasemonkey的沙箱/安全。請參閱GM pitfalls, event handlers

  3. 您需要use unsafeWindow to call a page's JS functions,如show_links()

  4. 當使用經常失敗的複雜ajax函數時,最好將它們包裝在try - catch塊中。

  5. 之間www.watch-series.comwatch-series.com,所以無論該網頁交換機必須在@include指令。


全部放在一起,你的腳本將變成:

// ==UserScript== 
// @name   Easier WatchSeries 
// @namespace  n/a 
// @include  http://www.watch-series.com/episode/* 
// @include  http://watch-series.com/episode/* 
// ==/UserScript== 

function my_func() 
{ 
    try 
    { 
     unsafeWindow.show_links(document.getElementById('idepisod').value); 
    } 
    catch (zError) 
    { 
     alert (zError); //-- Use console.log() in place of alert(), if running Firebug. 

    } 
} 

window.addEventListener ("load", my_func, false); 
+0

謝謝您的非常完整的答案。它解釋了很多,但最終我仍然得到相同的錯誤。我只是試圖做一些簡單的工作,我不必點擊「顯示更多鏈接」鏈接,而是自動加載鏈接。 show_links()是一個函數,它是它們的JS文件的一部分,並且基本上爲附加鏈接提供AJAX請求。它需要一個參數,即'idepisod'(情節ID)。我會繼續討論它。誰知道,也許我錯誤地安裝了腳本或其他東西。 – vince88 2011-01-27 07:31:08