'Document.addEventListener() keyup and keydown don't work after click

I'm writing a tampermonkey script that I want to perform an action when a certain set of keys is pressed (cmd + alt + t). I'm seeing a problem where the code stops executing altogether after I click anywhere on the page and I have to either hard refresh or click a certain place on the page (search bar in CloudWatch) to get it working again.

Here's my code:

(async function() {
    var set = new Set();

    function funcA() {
        console.log('funcA');
    }

    function funcB() {
        console.log('funcB');
        if (set.has(91) && set.has(18) && set.has(84)) { // cmd + alt + t
            funcA();
        }
    }

    function onKeyUp(e) {
        console.log('onKeyUp');
        set.clear();

        console.log(new Array(...set).join(' '));
    }

    function onKeyDown(e) {
        console.log('onKeyDown');
        set.add(e.which);

        console.log(new Array(...set).join(' '));

        funcB();
    }

    function init() {
        console.log('init');

        console.log('Adding event listeners.');
        document.addEventListener('keyup', onKeyUp);
        document.addEventListener('keydown', onKeyDown);
    }


    if( document.readyState !== 'loading' ) {
        console.log( 'not loading' );
        init();
    } else {
        document.addEventListener('DOMContentLoaded', init);
    }
})();

The problem only seems to happen on certain pages, for example in AWS CloudWatch logs.

Any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source