1

I'm creating a complicated in-browser app and I'd like to use some keyboard shortcuts that are currently used by Chrome and/or the other major browsers. I searched online and couldn't find a way to override browser shortcuts, but I saw that Google Sheets has just the kind of functionality I want: a user can select an option to override browser shortcuts.

How does Google sheets make this work?

Update: To clarify, since this has gotten some downvotes: I'm aware of event.preventDefault(). The problem is that it does not seem to work for key combinations like Ctrl + t (open new tab).

enter image description here

Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95

1 Answers1

7

The general idea is to intercept the event and call event.preventDefault() on it if it corresponds to a shortcut that you want to override. For example, the following code will prevent you from navigating to your leftmost tab if you press control-1:

document.body.addEventListener('keydown', (event) => {
  // keyCode 49 corresponds to the "1" key
  if(event.keyCode==49 && event.ctrlKey) {
    event.preventDefault();
    console.log('default action prevented, doing custom action instead');
  }
});
body {
  background-color: yellow;
}
click me first

Repeat for as many keyCodes and modifiers as you want.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I tried adding your code to my app and while it worked for `Ctrl + 1`, it did not work for `Ctrl + t`. However I also noticed that Google Sheets does not override `Ctrl + t`, so maybe it's a browser shortcut that cannot be overridden. – Nathan Wailes Oct 13 '18 at 06:40
  • 1
    Huh, interesting. So `Ctrl + 1` is, *somehow*, in a different realm from `Ctrl + t`. I wonder why. – CertainPerformance Oct 13 '18 at 08:29