Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Ctrl+S preventDefault in Chrome

I Want to catch Ctrl+S in Chrome, and prevent the default browser behavior to save the page. How?

(Just posting the question & answer as I was after this for a pretty long time and didn't find a solution)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As far as I can see, the secret sauce is, that Ctrl+S does NOT fire the keypress event, only the keydown event.

Using jQuery.hotkeys:

$(document).bind('keydown', 'ctrl+s', function(e) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
});

Only with jQuery:

$(document).bind('keydown', function(e) {
  if(e.ctrlKey && (e.which == 83)) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
  }
});

Edit 2012.12.17 - jQuery.hotkeys says

Hotkeys aren't tracked if you're inside of an input element (unless you explicitly bind the hotkey directly to the input). This helps to avoid conflict with normal user typing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...