javascript capture browser shortcuts (ctrl+t/n/w)
Asked Answered
O

5

74

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.

Ogburn answered 3/9, 2011 at 19:52 Comment(3)
Forget about CTRL + key commands. That's above JavaScript...Fluting
I can override Ctrl+S, Ctrl+R andso. I think only 3-4 shortcut cannot be overriden.Druse
If you've ever entered a question or answer on StackOverflow, you would surely have found that it is possible. Have you ever typed Ctrl+L? You'd expect the cursor to jump to the address bar, but StackOverflow captures it, expecting a URL for a link in your question or answer. Ctrl shortcuts are captured on DropBox and Google Docs as well. In the spirit of @Juhana's comment, it's unfortunate. (This is true under Linux, anyhow. I don't know about Windows, nor how it works with Apple's proprietary modifier keys.)Brozak
O
117

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.

Ogburn answered 3/9, 2011 at 22:41 Comment(10)
I have IE 9.0.6 and I can catch and cancel Ctrl+[R,T,S,N] (Not P) on keydown and up, and on both document and window.Apeman
@Yousef, could you block Ctrl+O? It seems that this other key cannot be trapped in IE9.Church
@Yousef Could you please update how you did this for IE9 catching CTRL + events ? ThanksGuidepost
@MuthuRaman Here is my script: jsfiddle.net/pssxpgus Canceling in IE is done by try { event.keyCode = 0; } catch(e) {} event.cancelBubble = true; event.returnValue = false;Apeman
@AlexisWilke I checked, apparently Ctrl+O is not being canceled in IE.Apeman
ctrl+c/v is not detected in chrome 51 while it's captured in firefox 50Atrophied
@Gergely Fehérvári @Atrophied Ctrl+W and Ctrl+T do not work anymoreSulphonate
On Firefox ctrl+n cannot prevent.Melamine
How does this keep the sequence?Staw
.keyCode is deprecated. Use .code or .key instead.Hoahoactzin
R
11

As of March, 20th, 2012, there has been a Chrome fix that allows web applications to handle Control+NWT in Chrome in js keydown event (so it works in pure javascript, or any library like jQuery).

This fix allows javascript to handle this key combinations if Chrome is opened in Application mode, which can be done in this way:

The fix is documented here:

Raulrausch answered 7/6, 2012 at 14:18 Comment(6)
Thanks for this. Sadly for those of us that wish to prevent our users from CTRL + W, this is the only option. I want other options because I run admin tools through a browser interface which people could accidentally close. :{ Those in my position can have a "do you really want to close this?" confirmation box.Overby
@VaelVictus: For your particular use case, you should be able to detect the tab close event via window.onbeforeunloadShatter
@Mark Thanks! However, it seems it won't work in Chrome for me. :/ It simply has to be on CTRL + W, and on every page regardless of whether they're "editing" or have something to save. Here's my fiddle: jsfiddle.net/2qb3jOverby
@VaelVictus: Yeah, I don't think you can detect if the Ctrl key is pressed through the event, because it's not a keypress that's triggering the event, it's the window closing, which has a different set of properties. You can, however, track the keyboard state to see if Ctrl is pressed: jsfiddle.net/2qb3j/7 Although the onkeyup doesn't trigger properly if the window isn't focused...so you might need some fiddling.Shatter
No. It's not the window closing which triggers the event, but the key press itself. The key press event happens before the window tries to close, so you can suppress the default event handling of this key press (closing the window) and do whatever you want instead. I have an app in production which is working perfectly as explained, with the 3 keys. So it's not only theory. Have you opened your fiddle in application mode? If not your fiddle is completely useless. It only works in application mode.Raulrausch
It would be nice if chrome would give the USER the option to adjust their shortcuts, even indie video games do this.Maul
E
9

To expand on the other answers:

The code to block certain combinations in Chrome/Chromium is defined here, im summary, F11 to exit fullscreen mode and everything manipulating and navigating tabs or windows is blocked:

[Shift]Ctrl(Q|N|W|T|Tab ↹)

Eliaseliason answered 19/8, 2016 at 7:44 Comment(0)
I
2

Instead of trapping the Ctrl+W hotkey, detect when the window is closed might be a valid option:

"The beforeunload event is fired when the window, the document and its resources are about to be unloaded.

When a non-empty string is assigned to the returnValue Event property, a dialog box appears, asking the users for confirmation to leave the page (see example below). When no value is provided, the event is processed silently."

Illyria answered 16/11, 2013 at 8:18 Comment(0)
H
1

The answer is really simple: This is not possible directly without some tricks in javascript.

It depends on the browser. Mostly all browser catch this shortcuts and use it for their own events. (e.g open new tabs) The shortcut never reach the javascript engine.

What is easy possible however, to catch the shortcuts with flash. But this is wide away from a user friendly website.

Update:

Here a short example. Mostly all browser will show the alert when Ctrl+y is pressed. (y = 89)

document.onkeydown = keyDownEvent;
document.onkeyup = keyUpEvent;

var isCtrl = false;

function keyDownEvent() {
    var keyid = event.keyCode;

    if(keyid == 17) {
        isCtrl = true;
    }
}

function keyUpEvent() {
    var keyid = event.keyCode;

    if(keyid == 17) {
        isCtrl = false;
    }

    if(keyid == 89 && isCtrl == true) {
        alert('CTRL-Y pressed');   
    }
}

If you replace the 84 by 89, which represents a t, nothing will happen. You can try it on jsfiddle.net.

Homogeny answered 3/9, 2011 at 20:1 Comment(1)
Yeah some people discussed it here code.google.com/p/chromium/issues/detail?id=33056Oilstone

© 2022 - 2024 — McMap. All rights reserved.