javascript 捕获浏览器快捷方式 (ctrl+t/n/w) [英] javascript capture browser shortcuts (ctrl+t/n/w)
问题描述
是否可以捕获这些快捷方式?
Is it possible to capture these shortcuts?
- Ctrl+N
- Ctrl+T
- Ctrl+W
我试过了,但没有用:
$(window).keydown(function(event) {
console.log(event.keyCode);
event.preventDefault();
});
当我按下 T 时,它会在控制台中显示 84
,但是如果我按下 Ctrl+T 它什么都不显示,然后打开一个新标签.
When I press T it shows 84
in the console, but if I press Ctrl+T it shows nothing, and opens a new tab.
我想捕获这些快捷方式并阻止任何浏览器操作.
I would like to capture these shortcuts and prevent any browser action.
推荐答案
在 Javascript 中捕获 Ctrl 键盘事件
示例代码:
$(window).keydown(function(event) {
if(event.ctrlKey && event.keyCode == 84) {
console.log("Hey! Ctrl+T event captured!");
event.preventDefault();
}
if(event.ctrlKey && event.keyCode == 83) {
console.log("Hey! Ctrl+S event captured!");
event.preventDefault();
}
});
火狐
(6.0.1 测试)
在 Firefox 中,两个事件监听器都可以工作.如果您按 CtrlT 或 CtrlS 组合键,您将在控制台和浏览器上同时收到消息不会打开标签页,也不会要求保存.
In Firefox both event listener works. If you press CtrlT or CtrlS keycombinations, you will get both message on the console, and the browser wont open a tab, nor ask for save.
有趣的是,如果您使用 alert
而不是 console.log
,event.preventDefault()
将不起作用,并且打开一个新标签或要求保存.也许这个错误需要修复.
It is intresting that if you use alert
instead of console.log
the event.preventDefault()
not works, and opens a new tab or asks for save. Maybe this bug needs to get fixed.
在 Chrome 3 中,它的工作方式类似于在 Firefox 中.
In Chrome 3 it works like in Firefox.
(已测试)
在 Chrome4 中,某些控制键组合已为浏览器保留仅供使用,不能再被客户端 JavaScript 拦截在网页中.
这些限制在 Chrome3 中不存在并且与两者不一致Firefox3/3.5 和 IE7/8(在 Windows 上).
In Chrome4, certain control key combinations have been reserved for browser usage only and can no longer be intercepted by the client side JavaScript in the web page.
These restrictions did not exist in Chrome3 and are inconsistent with both Firefox3/3.5 and IE7/8 (on Windows).
在 Chrome 4 中,它的工作方式与 Firefox 类似,除了一些键盘组合:
In Chrome 4 it works similary to Firefox, except some keyboard combination:
CtrlN
CtrlShiftN
CtrlT
CtrlShiftT
CtrlW
CtrlShiftW
Javascript 无法捕获这些组合,但嵌入插件可以捕获这些.例如,如果您专注于 Youtube 视频并按 CtrlT,浏览器将不会打开新标签页.
These combinations cannot get captured by Javascript, but embed plugins can capture these. For example if you focus in a Youtube video and press CtrlT, the browser won't open a new tab.
它的工作原理类似于 Firefox 或 Chrome3.
It works like in Firefox or Chrome3.
(已测试)
IE9 再次成为害群之马,因为它不允许 javascript 捕获任何 Ctrl? 键盘事件.我用许多键盘组合(R、T、P、S、N、T)进行了测试,但都没有奏效.嵌入应用程序也无法捕获事件.使用 Youtube 视频进行测试.
IE9 is a black sheep again, because it dosen't allow javascript to capture any Ctrl? keyboard event. I tested with many keyboard combination (R,T,P,S,N,T) and neither worked. Also embed applications can't capture the event. Tested with Youtube videos.
Thanks to @Lime for the great link.
这篇关于javascript 捕获浏览器快捷方式 (ctrl+t/n/w)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!