Search code examples
javascriptgoogle-chromeaddeventlistenerevent-listeneruserscripts

addEventListener not handling keys right in old Chrome version


I'm trying to add an event listener to a web-site via a userscript like this:

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

And while in Firefox it indeed triggers the right alerts dependent on keys a user presses, in Chrome for some reason all I get is always "NO", whether Space, j, k, l or n, for example, are pressed.

What could be the problem here? Thanks.

(I'm limited to an old OSX at the moment, so both Firefox and Chrome are quite old -- Chrome is 49 -- but I doubt this should be an issue...)


Solution

  • The .key property was not available in Chrome 49; use .which.

    Like so:

    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...