首页 > 解决方案 > addEventListener 未在旧 Chrome 版本中正确处理键

问题描述

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

// ==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 中,出于某种原因,我得到的始终是“否”,例如,是否按下Space, j, k, 。l or n

这里可能是什么问题?谢谢。

(我目前仅限于旧的 OSX,所以 Firefox 和 Chrome 都很旧——Chrome 已经 49 岁了——但我怀疑这应该是一个问题......)

标签: javascriptgoogle-chromeaddeventlistenerevent-listeneruserscripts

解决方案


.key属性在 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...


推荐阅读