Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - javascript capture browser shortcuts (ctrl+t/n/w)

Is it possible to capture these shortcuts?

  • Ctrl+N
  • Ctrl+T
  • Ctrl+W

I tried this but it doesn't work:

$(window).keydown(function(event) {
  console.log(event.keyCode);
  event.preventDefault();
});

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.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

Capturing Ctrl keyboard events in Javascript

Sample code:

$(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(); 
  }
});

Firefox

(6.0.1 tested)

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.

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.


Chrome3

In Chrome 3 it works like in Firefox.


Chrome4

(tested)

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).

In Chrome 4 it works similary to Firefox, except some keyboard combination:

  • CtrlN

  • CtrlShiftN

  • CtrlT

  • CtrlShiftT

  • CtrlW

  • CtrlShiftW

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.


IE7/8

It works like in Firefox or Chrome3.


IE9

(tested)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...