How prevent default of C-w/t/n

I’m developing a first-person game, and my character needs to be able to squat. But when ctrl+w is combined, the browser tab closes. Is there a way to avoid this without changing the controls?

Use event.preventDefault() inside a onKeyDown event listenner when event.key equal desired key.

window.onKeyDown = (event) => {
  const {key, keyCode, metaKey, shiftKey, altKey, ctrlKey} = event; 
  if(key === "w" && (ctrlKey || metaKey)) {
    e.preventDefault();
  }
};
4 Likes

This method does not work for me. Have you tested it in action?Maybe I’m doing something wrong, but as far as I know, a simple prevent default does not block closing the tab. Anyway, thanks for the answer!

Browsers can be selective about which default behaviors they allow websites to override. There’s no guarantee that all browsers will allow you to override the Ctrl + W shortcut, especially because it’s such a crucial and common action.

3 Likes

Well, thanks! Then I’ll think about a different control layout :grin:

I wrote it from memory my bad…

In my project I use a code tweaked to consider a list of keys to forbid. It works on 3 Chronium based browser I tested: edge, chrome and brave.

Code above probably need to use addEventListener function.