【问题标题】:console.log is not working when used in a Firefox, Greasemonkey script在 Firefox、Greasemonkey 脚本中使用时,console.log 不起作用
【发布时间】:2012-04-25 11:42:17
【问题描述】:

我的用户脚本使用console.log() 打印一些信息。

这在 Chrome 中运行良好,但是当我在 Firefox (Greasemonkey) 中安装此用户脚本时,Firefox 中的 Web 控制台没有显示任何内容。

我搜索了一个解决方案,有人建议使用unsafeWindow,但它也没有显示任何输出。此外,unsafeWindow 不能用于 chrome。我什至安装了 Firebug,但没有用。我该如何解决这个问题?

例如,我在 Firefox 中尝试了这个用户脚本:

// ==UserScript==
// @name        console
// ==UserScript==
console.log("hello");

【问题讨论】:

    标签: firefox greasemonkey userscripts


    【解决方案1】:

    您的意思是通过 Greasemonkey 安装时它不起作用,对吗?
    不久前,Greasemonkey broke console.log(新!Bug report)。现在,要查看来自 Greasemonkey 的普通 console.log() 调用的结果,您需要查看 Firefox 的错误控制台,而不是 Firebug 的。

    你可以通过按:CtrlShiftJ看到FF的错误控制台。

    但是,您可以在 Chrome 和 Greasemonkey 脚本中使用 unsafeWindow.console.log()。 Chrome 现在对unsafeWindow 的支持有限。

    如果您使用unsafeWindow,您可以访问Greasemonkey 的全部Firebug's logging functions。 (必须安装 Firebug,但它们可能仍然无法在 Chrome 用户脚本中运行;我已经有一段时间没有测试过这种方式了。)


    在 Firefox 中,如果 Firebug 未安装,或者该页面未激活,则 unsafeWindow.console.log() 调用将显示到新的“Web 控制台”(CtrlShiftK)。
    在 Greasemonkey 脚本中,您需要使用 unsafeWindow

    请注意,Firefox 目前原生支持 console.log()console.info()console.warn()console.error() -- 不需要 Firebug。

    【讨论】:

    • 如果我在 firebug 中使用 unsafeWindow.console.log(),它可以工作,但我如何在 webConsole 中获得输出。有没有办法不使用萤火虫得到输出。
    • 我试过了,它有效。请记住,必须为页面禁用 Firebug,并且您必须使用 unsafeWindow,除非您的脚本被注入。
    • 我删除了 firebug 并添加了 unsafeWindow 我的代码现在是 // ==UserScript== // @name console // ==UserScript== unsafeWindow.console.log('hello'); 我的 Web 控制台中仍然没有显示任何内容
    • 现在我在我的 Web 控制台中得到它,只记录错误被标记,所以我没有得到输出。但是unsafeWindow 总是在 chrome 中工作吗?谢谢你,很抱歉犯了愚蠢的错误。
    • 是的,unsafeWindow 始终在 Chrome 中工作为此(记录目的)。
    【解决方案2】:

    等一下:如果问题是关于使用 Greasemonkey 登录控制台(我可以发誓我看到了标签 ),为什么不使用 GM_log 方法?

    // ==UserScript==
    // @name          GM_log Example
    // @namespace     http://www.example.com/
    // ==/UserScript==
    
    GM_log("This is an example of GM_log");
    

    还是我错过了什么?

    PS:你也可以在 about:config 中检查javascript.options.showInConsole。应该是true

    【讨论】:

    • 是的,您可以使用GM_log,但它不可移植或不可单元测试。此外,与console API 相比,它也很糟糕——大多数浏览器现在都支持本机 API,以及 Firebug、超甜的控制台 API。
    【解决方案3】:

    我发现(使用 Chrome/Tampermonkey 测试)您需要:

    window.log("<message goes here>");,不是unsafeWindow.console.log("<msg>");, 因为unsafeWindowconsole 出现为未定义。

    尝试一下,因为我很确定这是您在更高版本的浏览器等中应该这样做的方式。

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 2013-12-06
      • 2023-03-08
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      相关资源
      最近更新 更多