2

Linked Questions

  1. Listen - How can I listen for keypress event on the whole page?
  2. Override - How does Google Sheets override browser shortcuts?

I'm trying to create a web page that helps people build Macros for LUAMacros. part of this is to interpret Key presses within the browser, these may trigger browser shortcuts

        <script>
        document.body.addEventListener('keydown', (event) => {
                       event.preventDefault();
        });
    </script>

this will prevent the browser from responding to built in shortcuts. however also prevents the angular component listening to the key press

@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
    this.key = event.key;
    console.log(this.key);
    event.preventDefault();
}

Without the script, the browser responds to shortcuts, however with it the component will not fire the above host listener.

the components ' event.preventDefault();' appears to respond after the browser recognises the short cut.

Incidentally i'm trying to resolve [CTRL + k] which chrome uses for search.

RoughPlace
  • 1,111
  • 1
  • 13
  • 23

1 Answers1

0

You can utilize the fact that events bubble up the DOM tree. In your Angular code, listen to events as you already do: by attaching an event listener to document. In the global part of the page, simply listen to window instead of document.

Every event that happens will firstly be triggered on document (allowing you to perform custom action). Unless Event#stopPropagation is called on it, it will then bubble up to window (where you'll catch it and prevent its default behavior, as defined by browser).

<script>
  window.addEventListener('keydown', event => {
    event.preventDefault()
  })
</script>
@HostListener('document:keypress', ['$event'])
public handleKeyboardEvent (event: Event) {
  event.preventDefault()
}
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
  • I can see what you are trying to do here although it appears not to be working. i have added the above snippets and some variants into various combinations of the index.html and the component and the experience is the same as described in the original question. thanks however :) – RoughPlace Apr 22 '20 at 10:39