Ctrl+S preventDefault in Chrome

最后都变了- 提交于 2019-11-27 04:18:39

问题


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)


回答1:


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.




回答2:


"Borrowed" from Overriding control+s (save functionality) in browser

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



回答3:


document.onkeydown = function (e) {
    e = e || window.event;//Get event
    if (e.ctrlKey) {
        var c = e.which || e.keyCode;//Get key code
        switch (c) {
            case 83://Block Ctrl+S
                e.preventDefault();     
                e.stopPropagation();
            break;
        }
    }
};
   


来源:https://stackoverflow.com/questions/11000826/ctrls-preventdefault-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!