【问题标题】:Printing the `event` object inside a greasemonkey script silently terminates execution, how can I view the `event`?在greasemonkey脚本中打印`event`对象会静默终止执行,我如何查看`event`?
【发布时间】:2019-05-10 15:36:49
【问题描述】:

这是我的脚本(特意简化):

// ==UserScript==
// @name            StackOverflowExample
// @include     https://stackoverflow.com/*
// @version     1
// @grant       none
// ==/UserScript==


document.addEventListener('keydown', (e) => {
  console.log('I print before the "e"')
  conosel.log({e})
  console.log('I print after the "e"')
})

当这个脚本加载到我的页面(堆栈溢出)时,我看到“我在“e”之前打印”被打印到控制台,但我没有看到“e”或“我在之后打印” “e”'被记录下来。这是为什么呢?

我尝试添加 e.preventDefault() 之类的内容,但没有任何区别。

令人费解的是,事件监听器内部的这种东西居然还能用:

document.addEventListener('keydown', (e) => {
if(e.keyCode !== 40)){
console.log('you pressed some random key')
} else {
console.log('you pressed the "UP" arrow key')
}
})

所以e 对象被定义(只需按任意键,然后按“向上”)。有什么想法吗?

编辑:似乎我的第二部分错了,(虽然我很确定我看到它在另一个网站上工作......)

浏览器 = firefox 63.0.3(64 位)

操作系统 = Ubuntu 18.04

GreaseMonkey = 4.7

【问题讨论】:

    标签: javascript firefox userscripts tampermonkey greasemonkey-4


    【解决方案1】:

    Greasemonkey 4+ 是粗鲁的,the GM team itself recommends not to use it

    如果您使用 Tampermonkey(也可能是 Violentmonkey)安装了脚本,您会在控制台上看到语法错误。 (如果你使用的话,也可以在 Tampermonkey 的编辑器窗口中。)

    请注意,Greasemonkey 4+ 实际上并没有静默失败。 它只是将错误消息隐藏在 Firefox 的“浏览器控制台”中Ctrl+Shift+J),其中大多数人不会知道/想去寻找它们。

    显然,conosel 是一个错误(原始代码块的第 11 行)。

    同样,if(e.keyCode !== 40)) 是第二个代码块中的语法错误。

    还有:

    1. console.log({e}) 很差,因为它在虚拟对象中不必要地掩盖了 e
    2. (e) 中的括号是多余的。
    3. 代码格式、间距和缩进可以帮助您更快地发现错误,并且总体上更容易阅读/维护您的代码。
    4. keyCode 40 是 向下 箭头键,而不是向上箭头。
    5. 养成using semicolons; it will save needless errors and head scratching的习惯。

    所以,第一个代码块应该是:

    // ==UserScript==
    // @name        StackOverflowExample
    // @match       https://stackoverflow.com/*
    // @version     1
    // @grant       none
    // ==/UserScript==
    
    document.addEventListener ('keydown', e => {
        console.log ('I print before the "e"');
        console.log ("e: ", e);
        console.log ('I print after the "e"');
    } );
    

    第二个:

    document.addEventListener ('keydown', e => {
        if (e.keyCode !== 38) {
            console.log ('you pressed some random key');
        }
        else {
            console.log ('you pressed the "UP" arrow key');
        }
    } );
    

    并使用 Tampermonkey 和/或 Violentmonkey,而不是 Greasemonkey。您将节省数小时的挫败感,并且您的脚本将更加可靠和便携。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多