3.2. 用 GM_log 记日志

Greasemonkey 提供了一个记录用的函数,GM_log,这个函数可以将消息写入错误控制台。这些消息在发布前应当剔出掉,不过在调试时却非常有用。此外,看调试信息比在调试用的警告窗口中一次次点确定好得多。

GM_log有一个参数:日志的字符串。在将信息输出到错误控制台后,用户脚本会一如既往地执行。

例 3.1. 记录到错误控制台然后继续( gmlog.user.js )

if (/^http:\/\/diveintogreasemonkey\.org\//.test(window.location.href)) {
	GM_log('running on Dive Into Greasemonkey site w/o www prefix');
} else {
	GM_log('running elsewhere');
}
GM_log('this line is always printed');

安装这个用户脚本后打开 http://diveintogreasemonkey.org/,这两行就会出现在错误控制台中:

Greasemonkey: http://diveintomark.org/projects/greasemonkey//Test Log:
running on Dive Into Greasemonkey site w/o www prefix
Greasemonkey: http://diveintomark.org/projects/greasemonkey//Test Log:
this line is always printed

如您所见,Greasemonkey 从用户脚本元数据段中取得命名空间和脚本名称,再把作为传给GM_log的参数日志消息算进来,做为显示在错误控制台中显示的信息。

如果您访问的不是http://diveintogreasemonkey.org/,那么下面这两条信息会显示在错误控制台中。

Greasemonkey: http://diveintomark.org/projects/greasemonkey//Test Log:
running elsewhere
Greasemonkey: http://diveintomark.org/projects/greasemonkey//Test Log:
this line is always printed

我已经厌倦去挖掘日志信息的最大长度。它超过了255个字符。还有,输出的信息在错误控制台中可以正确断行,可以向下滚动来查看日志消息其余部分。为日志着迷吧!

[提示]

在错误控制台中可以用右键(Mac用户用 control-click)点击任意行选中,然后选择复制(C),将信息复制到剪贴板。

参见

← 用错误控制台追踪错误
用 DOM 查看器查看元素 →