2

Is there any way to prevent a key like F1 from being pressed?

After a short search, I found this website:

http://www.cambiaresearch.com/c4/789d4357-60e9-4dbd-8e8c-affb2ebd6960/How-Do-I-Suppress-a-Keystroke-in-a-Browser-Input-Box-Using-Javascript.aspx

This way one can suppress keys like 'a' being pressed (it does not get put in the textbox), but keys like 'tab', 'F1' etc. are still working, i.e. the focus does change and, as I'm using Google Chrome, the Chrome help website does pop up.

I'm specifically talking about Google Chrome; the solution does not have to work in other browsers too.

Is this possible at all, and if so, how?

Thanks.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • I hadn't thought about Alt+F4 combinations, but suppressing F5 does work with the answer provided. Edit: Even Alt+F4 works! Weird, really. Not sure if this was foreseen when making Chrome. – pimvdb Feb 05 '11 at 13:45

2 Answers2

4

keypress is not necessarily triggered when the keypress is not a character. So the browser may not trigger an event on backspace, F1, the down key, etc.

Try cancelling events on keydown instead:

element.addEventListener('keydown', function(e) {
    if (e.which === 112) { // F1 pressed
        e.preventDefault(); // cancel the event
    }
}

Note that this will work in Chrome and other standards-compliant browsers, but not in Internet Explorer <9.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • This even prevents Alt+F4 combinations in Chrome for me, wouldn't have thought that... – pimvdb Feb 05 '11 at 13:47
  • +1 good to know! At least (for me) it doesn't seem to work for key combinations like CTRL+TAB. – Reiner Gerecke Feb 05 '11 at 13:49
  • @pimvdb that's weird. It doesn't work for me, but maybe that depends on the operating system? ALT+F4 works fine here (Ubuntu+Chrome). – Reiner Gerecke Feb 05 '11 at 13:51
  • @Reiner Ctrl+Tab and Ctrl+Shift+Tab then again can't be suppressed - weird... And I'm on Windows, Alt+F4 *does* get suppressed here. – pimvdb Feb 05 '11 at 13:51
0

I highly doubt that this is possible. Not only would one be able to interfere normal program behaviour (say, F5 to refresh the page, or ALT+F4 to close the browser), but in a quick test it looks like for keys like F1 etc. no event is fired, so there is no way for a input to receive that.

Reiner Gerecke
  • 11,936
  • 1
  • 49
  • 41
  • 1
    I agree with you, but it is remarkable that events *do* get fired for me. 'tab' has a keyCode of 9, whereas 'F1' has a keyCode of 112 fired in my version of Chrome. Edit: sorry I'm using the keydown, never mind my comment. – pimvdb Feb 05 '11 at 13:42
  • 2
    The events are not necessarily fired on `keypress` (it's implementation-specific) but *are* fired on `keydown`. – lonesomeday Feb 05 '11 at 13:43