19

I know a lot of people will be angry about this being asked but...

I have a game using WebGL and the Pointer Lock API. Due to the nature of a lot of games having 'crouch' on CTRL I was wondering if there was any possible way to stop browser shortcuts like CTRL + S and CTRL + W...

At the moment I'm having to harshly disallow controls to have any CTRL key in them. I have set 'crouch' to C which is also common but I also have ideas about making a MMORPG-style game where you would have several action bars of abilities and a lot of combinations wouldn't be possible due to CTRL not being viable.

gman
  • 100,619
  • 31
  • 269
  • 393
user2000236
  • 261
  • 1
  • 3
  • 8
  • Listen to `keydown`s; if the keys match, then `event.preventDefault()` and call the appropriate action(s). Alternatively, you could look into [mousetrap](http://craig.is/killing/mice), which is arguably the best key-capturing library for JavaScript. – royhowie Jul 15 '14 at 17:49

1 Answers1

41

Note: In Chrome Ctrl+W is "reserved", use window.onbeforeunload

Note: Chrome requires event.returnValue to be set

In this code document.onkeydown is used for old browsers and window.onbeforeunload is used to Chrome and Firefox

Try this (disable Ctrl+W and Ctrl+S):

window.onbeforeunload = function (e) {
    // Cancel the event
    e.preventDefault();

    // Chrome requires returnValue to be set
    e.returnValue = 'Really want to quit the game?';
};

//Prevent Ctrl+S (and Ctrl+W for old browsers and Edge)
document.onkeydown = function (e) {
    e = e || window.event;//Get event

    if (!e.ctrlKey) return;

    var code = e.which || e.keyCode;//Get key code

    switch (code) {
        case 83://Block Ctrl+S
        case 87://Block Ctrl+W -- Not work in Chrome and new Firefox
            e.preventDefault();
            e.stopPropagation();
            break;
    }
};
Protomen
  • 9,471
  • 9
  • 57
  • 124
  • 2
    Hi i'm not sure about marking this correct because I found other places stating you can't prevent CTRL+W and some others. This worked for CTRL+S and but not CTRL+W – user2000236 Jul 15 '14 at 20:40
  • The `onkeydown` part does not seem to work neither in Chrome v72, nor in Firefox v65 (on xubuntu v18.04.1 at least). – Klesun Mar 20 '19 at 10:11
  • 2
    @ArturKlesun update code, Chrome requires `event.returnValue` to be set .... Note: `document.onkeydown` is used by old browsers – Protomen Mar 22 '19 at 21:30