我想在Chrome浏览器中捕获 Ctrl+S 快捷键,并阻止默认的浏览器保存页面行为。该怎么做?
(我发帖问问题并提供答案,因为我曾经寻找了相当长时间,但没有找到解决方案)
我想在Chrome浏览器中捕获 Ctrl+S 快捷键,并阻止默认的浏览器保存页面行为。该怎么做?
(我发帖问问题并提供答案,因为我曾经寻找了相当长时间,但没有找到解决方案)
就我所看到的,秘密的关键是 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 说明:
如果您在输入元素内部(除非您将热键直接绑定到输入元素),否则不会跟踪热键。这有助于避免与正常的用户打字产生冲突。
keyup
,这将始终首先触发保存对话框。始终选择 keydown
。 - Avatar从这里借鉴过来的
document.addEventListener("keydown", function(e) {
if (e.key === 's' && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
e.preventDefault();
alert('captured');
}
}, false);
keyCode
已被弃用,现在推荐使用keyboardEvent.key === 's'
。实际上,既然我可以编辑,为什么还要评论呢 >:D - Klesundocument.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;
}
}
};
防止数据泄露的全能解决方案
// 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;
}
});