首页 文章

在greasemonkey脚本中打印`event`对象会默默地终止执行,如何查看`event`?

提问于
浏览
0

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

// ==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"')
})

当这个脚本被加载到我的页面(Stack Overflow)时,我看到'我在'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对象(只需按任意键然后按“向上”) . 有任何想法吗?

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

Browser = firefox 63.0.3(64位)

OS = Ubuntu 18.04

GreaseMonkey = 4.7

1 回答

  • 0

    Greasemonkey 4是crud和the GM team itself recommends not to use it .

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

    请注意,Greasemonkey 4实际上并没有默默地失败 . It just hid the error messages away in Firefox's "Browser Console" (Ctrl Shift J),大多数人都不会知道/想要寻找它们 .

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

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

    也:

    • console.log({e}) 很差,因为它在虚拟对象中不必要地模糊了 e .

    • (e) 中的括号是多余的 .

    • 代码格式,间距和缩进可以帮助您更快地发现错误,并且可以轻松地尝试读取/维护代码 .

    • keyCode 40是 down 箭头键,而不是向上箭头 .

    • 养成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 . 您可以节省数小时的挫败感,并且您的脚本将更可靠,更便携 .

相关问题