javascriptreactjstypescriptgoogle-chrome-extensionbrowser-extension

How to avoid input keyboard shortcut stealing by websites in chrome extension develpment


I'm working on browser extension development and insert an input form in a modal for the extension, but I found website shortcut key event has higher priority than input key press, so I cannot get the input letter. For example, if press letter L in TikTok, it will trigger like a video instead to add L to the input text field, any solution to avoid this and capture input press first?


Solution

  • The sample code works as @wOxxOm mentioned above

    function untilDocumentReady() {
        function fn(e: KeyboardEvent) {
           var key = e.key;
           console.log("You pressed a key: " + key)
           e.stopPropagation()
        }
    
        window.addEventListener('keydown', fn, true)
    }
    

    or

    function untilDocumentReady() {
       ...
    
        window.addEventListener('keydown', (event) => {
          var key = event.key;
          console.log("untilDocumentReady - You pressed a key: " + key)
          event.stopPropagation()
        }, true);
      })
    }