46

我想在 Chrome 中捕获Ctrl+ S,并阻止默认浏览器行为来保存页面。如何?

(只是发布问题和答案,因为我在此之后很长时间并没有找到解决方案)

4

4 回答 4

59

据我所知,秘诀是,Ctrl+S不会触发 keypress 事件,只会触发 keydown 事件。

使用jQuery.hotkeys

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

仅使用 jQuery:

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

编辑 2012.12.17 - jQuery.hotkeys 说

如果您在输入元素内部,则不会跟踪热键(除非您将热键直接绑定到输入)。这有助于避免与正常用户键入的冲突。

于 2012-06-12T16:29:14.770 回答
26

从浏览器中的覆盖控件+s(保存功能)中“借用”

document.addEventListener("keydown", function(e) {
  if (e.key === 's' && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
    alert('captured');
  }
}, false);
于 2012-06-12T16:42:39.307 回答
4

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;
        }
    }
};
   

于 2015-03-31T07:26:13.477 回答
1

多合一的解决方案,以防止数据

// disable right click
$(function() {
    $(this).bind("contextmenu", function(e) {
        e.preventDefault();
    });
}); 

// Prevent F12      
$(document).keydown(function (event) {
    if (event.keyCode == 123) { // Prevent F12
        return false;
    } else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) { // Prevent Ctrl+Shift+I        
        return false;
    }
});

//stop copy of content
function killCopy(e){
    return false
}
function reEnable(){
    return true
}
document.onselectstart=new Function ("return false")
    if (window.sidebar){
    document.onmousedown=killCopy
    document.onclick=reEnable
}

// prevent ctrl + s
$(document).bind('keydown', function(e) {
  if(e.ctrlKey && (e.which == 83)) {
    e.preventDefault();
    return false;
  }
});
于 2019-12-12T13:23:03.913 回答