31

I am trying to override the browser save shortcut i.e. Ctrl+S to give the functionality of save in my web App , I am using Google Chrome... I tried keydown listener to observe the keycode but when two keys i.e. Ctrl+S are pressed simultaneously, keycode of S is never returned in event object.

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Vinay Verma
  • 1,084
  • 3
  • 12
  • 16

1 Answers1

49

You receive two keydown events: The first is for the control key, and the second is for the letter with the modifier flag turned on. Here's how you listen for a key with a modifier pressed:

document.addEventListener("keydown", function(e) {
  if (e.keyCode === 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
    // Process event...
  }
}, false);

keyCode === 83 corresponds to S key press.

Taking a page from Google Docs, it uses Cmd-S on Mac and Ctrl-S on other platforms.

Audwin Oyong
  • 2,061
  • 3
  • 10
  • 31
Josh Lee
  • 161,055
  • 37
  • 262
  • 269
  • what is the 3rd arg for? false? –  Aug 23 '19 at 20:31
  • @user11810894 that specifies whether the event handler should be called in the capture or bubbling phase of the event - see [here](https://www.quirksmode.org/js/events_order.html) for more information on that. It defaults to `false` though, so it technically isn't needed here. – peabrainiac Dec 24 '19 at 16:08