Javascript 在greasemonkey脚本中打印'event'对象会自动终止执行,如何查看'event'?
以下是我的脚本(有意简化): 当这个脚本加载到我的页面(堆栈溢出)时,我看到“e”之前的I print(我打印)被打印到控制台,但我没有看到“e”或“e”之后的I print(我打印)被记录。为什么会这样 我尝试过添加类似Javascript 在greasemonkey脚本中打印'event'对象会自动终止执行,如何查看'event'?,javascript,firefox,userscripts,tampermonkey,greasemonkey-4,Javascript,Firefox,Userscripts,Tampermonkey,Greasemonkey 4,以下是我的脚本(有意简化): 当这个脚本加载到我的页面(堆栈溢出)时,我看到“e”之前的I print(我打印)被打印到控制台,但我没有看到“e”或“e”之后的I print(我打印)被记录。为什么会这样 我尝试过添加类似e.preventDefault()的东西,但没有什么不同 令人费解的是,事件监听器中的这种事情仍然有效: 因此定义了e对象(只需按任意键,然后“向上”)。有什么想法吗 编辑:看来我对第二部分错了,(虽然我很确定我在另一个网站上看到了它的工作…) 浏览器=firefox 63.
e.preventDefault()
的东西,但没有什么不同
令人费解的是,事件监听器中的这种事情仍然有效:
因此定义了e
对象(只需按任意键,然后“向上”)。有什么想法吗
编辑:看来我对第二部分错了,(虽然我很确定我在另一个网站上看到了它的工作…)
浏览器=firefox 63.0.3(64位)
OS=Ubuntu 18.04
GreaseMonkey=4.7GreaseMonkey 4+是积垢和杂质 如果您使用Tampermonkey(也可能是Violentmonkey)安装了脚本,您会在控制台上看到语法错误。(如果使用,也可以在Tampermonkey的编辑器窗口中使用。) 请注意,Greasemonkey 4+实际上并没有自动失败它只是将错误消息隐藏在Firefox的“浏览器控制台”(Ctrl+Shift+J)中,大多数人都不知道/想在那里查找它们 显然,
conosel
是一个错误(原始代码块的第11行)
同样地,if(e.keyCode!==40))
是第二个代码块中的语法错误
此外:
console.log({e})
很差,因为它不必要地遮挡了虚拟对象中的e
(e)
中的括号是多余的keyCode
40是向下箭头键,而不是向上箭头键// ==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。您将节省数小时的挫折感,并且您的脚本将更加可靠和可移植
// ==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');
}
} );