不到十分钟前,我决定为 Greasemonkey 编写我的第一个脚本。我对此零经验。另外,我的 JavaScript 有点生疏,因为我上次用它编写代码已经有一段时间了。但我不明白为什么 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();
我想要做的就是向 body 标记添加一个 onLoad 属性。当我转到“管理新用户脚本”->“编辑”时出现此错误。除此之外,脚本什么都不做,所以显然有问题。
我正在运行 Firefox 3.6.13。
最佳答案
几件事:
-
- 在浏览器中打开about:config。
- 过滤 greasemonkey.editor。
- 输入有效编辑器的有效路径。我喜欢TextPad , 但
c:\Windows\System32\notepad.exe
应该适用于大多数 Windows 系统。 - 您可能需要重新启动 Firefox。
由于 Greasemonkey 的沙箱/安全性,无法以这种方式添加事件监听器。参见 GM pitfalls, event handlers .
您需要use
unsafeWindow
to call a page's JS functions ,例如show_links()
。当使用经常失败的复杂 ajax 函数时,最好将它们包装在
try - catch
block 中。该页面在 www.watch-series.com 和 watch-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);
关于javascript - “文档”在 Greasemonkey 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4812455/