Search code examples
javascripteventswindowkeydown

Redirect keydown event on other than window


So I am building a userscript (same as a javascript script) on a website and I was wondering if it was possible to prevent the keydown event to happen on the window while not modifying window.onkeydown = ...


Solution

  • A userscript isn't actually the "same as a javascript script", which userscript platform you are using plays an important role in answering this question. However, assuming it's one of the ore common and popular ones, you do it the same way you would in JavaScript, as along as you have it running at the right time...

    // ==UserScript==
    // @run-at document-start
    // ==/UserScript==
    document.addEventListener( 'keydown', event => {
      event.stopImmediatePropagation();
      // Do some other stuff instead
    } );