Not more than ten minutes ago I decided to write my first script for Greasemonkey. I have zero experience with it. Also, my JavaScript is a bit rusty as it's been a while since I last wrote code in it. But I can't figure out why Greasemonkey is giving me this error:
Line: 9
Char: 2
Error: 'document' is undefined
Code: 800A1391
Source: Microsoft JScript runtime error
Here's my script:
// ==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();
All I want to do is add an onLoad attribute to the body tag. I get this error when I go to "Manage New User Scripts" -> "Edit". Other than that the script does nothing so obviously so开发者_如何学Pythonmething is wrong.
I'm running Firefox 3.6.13.
Several things:
That cryptic error message has been found to happen when Greasemonkey does not have a proper editor set up.
- Open about:config in your browser.
- Filter on greasemonkey.editor.
- Enter a valid path to a valid editor. I like TextPad, but
c:\Windows\System32\notepad.exe
should work on most windows systems. - You might need to restart Firefox.
Event listeners cannot be added that way due to Greasemonkey's sandbox/security. See GM pitfalls, event handlers.
You need to use
unsafeWindow
to call a page's JS functions, likeshow_links()
.When using complicated ajax functions that often fail, it's a good idea to wrap them in
try - catch
blocks.That page switches between www.watch-series.com and watch-series.com, so both need to be in the
@include
directives.
Putting it all together, your script would become:
// ==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);
精彩评论