addEventListener 在旧 Chrome 版本中不正确处理键

addEventListener not handling keys right in old Chrome version

我正在尝试通过这样的用户脚本向网站添加事件侦听器:

// ==UserScript==
// @name        Reuters: j/k navigation
// @version     0.01
// @match       https://www.reuters.com/*
// @run-at      document-start
// @grant       none
// ==/UserScript==

addEventListener('keypress', e => {
    if (e.ctrlKey ||
        e.altKey ||
        e.metaKey ||
        e.shiftKey ||
        (e.key !== 'k' && e.key !== 'j')) {
        alert("NO");
        return;
    }
    alert("YES");
});

虽然在 Firefox 中,它确实会根据用户按下的键触发正确的警报,但在 Chrome 中,出于某种原因,我得到的总是 "NO",无论 Space, j, k, l 或者 n,例如,被按下。

这可能是什么问题?谢谢

(目前我只能使用旧的 OSX,所以 Firefox 和 Chrome 都很旧——Chrome 是 49——但我怀疑这应该成为一个问题...)

.key 属性 是 not available in Chrome 49;使用 .which

像这样:

const jKey = 'j'.charCodeAt (0);
const kKey = 'k'.charCodeAt (0);

addEventListener ('keypress', e => {
    if (e.ctrlKey ||
        e.altKey ||
        e.metaKey ||
        e.shiftKey ||
        (e.which !== jKey  &&  e.which !== kKey) ) {
        console.log (e.which, "NO");
        return;
    }
    console.log (e.which, "YES");
} );
Click here then press keys...