2

我正在尝试编写一个greasemonkey脚本,如果页面显示404错误,它会在Firefox中检查。如果是这样,脚本应该重新加载页面。脚本如下所示:

// ==UserScript==
// @name        404-reloader
// @namespace   None
// @include     *
// @version     1
// ==/UserScript==

url = "http://www.example.com";

if (document.getElementById("errorPageContainer"))
    location.href = url;

我的问题是,它只在某些时候有效。为了测试它,我关闭了我的无线适配器并加载了一个页面。脚本本身没有,所以我手动启动它。我第一次启动它时,脚本工作并更改为 example.com,在那里我得到了另一个未找到的错误,因为适配器仍然关闭。我再次启动脚本并且它工作。第三次之后,我在脚本中遇到了异常:

/*
Exception: Permission denied to access property 'document'
@Scratchpad/2:10
*/

我发现当我更改 URL 时,脚本会工作一次。之后我得到了这个例外。当脚本不起作用时,我将其复制到 firebug 控制台并运行它。它在那里工作,但仍然不在greasemonkey脚本中。

现在我想知道为什么greasemonkey 会有这样的行为,以及我如何处理异常问题以及Greasemonkey 不能在404 页面上自行运行的问题。

我已经搜索了答案,但没有找到任何对我的问题有用的东西。

谢谢您的帮助

4

1 回答 1

1

I thought it's a feature actually that GM doesn't run on error pages, anyway, this works for me:

Instead of running at document-end which is default, when you run at document-start and add a listener for DOMContentLoaded, it works well for me even when reloading. Note though that @run-at is GM-specific (>=1.0), not portable so far to Chrome/Opera as far as I know.

// ==UserScript==
// @name        test123
// @namespace   test123
// @version     1
// @include     *
// @grant       none
// @run-at      document-start
// ==/UserScript==

document.addEventListener("DOMContentLoaded", function () {
    console.log(document.getElementById('errorPageContainer'));
});
于 2013-06-27T21:19:32.313 回答