Neelu S Neelu S - 2 months ago 9
jQuery Question

Can't catch Cmd-S on Chrome on Mac

I'm trying to catch both Ctrl-S and Cmd-S on browsers for cross-OS Compatibility of my web app. I saw a thread about how to do that here: jquery keypress event for cmd+s AND ctrl+s

I have the following snippet in my code:

$(document).keypress(function(event) {
if (event.which == 115 && (event.ctrlKey||event.metaKey)|| (event.which == 19)) {
event.preventDefault();
save();
return false;
}
return true;
});


where
save()
is a JavaScript function that will send an AJAX request in the future, but just has
alert('Saved!');
for now.

However, although this catches Ctrl-S, it doesn't catch Cmd-S on Chrome, instead just opening the save webpage dialog like usual. I saw that someone else on that page had the same problem, but I didn't see a solution for it.

Thanks in advance!

Answer

I think keypress as you have it doesn't register metakeys in the quite the same way, see: Diffrence between keyup keydown keypress and input events here's a fiddle that seems to work using keydown, and then capturing each in sequence. Hope it helps?

var metaflag = false;

$(document).on({
	keydown: function(event) {
    if (event.ctrlKey||event.metaKey || event.which === 19) {
      event.preventDefault();
      $('.monitor').text('key '+event.which);
      metaflag = true;
    }
  	if( metaflag && event.which === 83 ){ // 83 = s?
      event.preventDefault(); // maybe not necessary
      $('.display').text('saving?');
      metaflag = false;
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='monitor'></div>
<div class='display'></div>