2011-01-27 97 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