开发者

'document' is undefined in Greasemonkey

开发者 https://www.devze.com 2023-02-07 12:06 出处:网络
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 i

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:

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

    1. Open about:config in your browser.
    2. Filter on greasemonkey.editor.
    3. Enter a valid path to a valid editor. I like TextPad, but c:\Windows\System32\notepad.exe should work on most windows systems.
    4. You might need to restart Firefox.

  2. Event listeners cannot be added that way due to Greasemonkey's sandbox/security. See GM pitfalls, event handlers.

  3. You need to use unsafeWindow to call a page's JS functions, like show_links().

  4. When using complicated ajax functions that often fail, it's a good idea to wrap them in try - catch blocks.

  5. 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消