Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

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

1 Answer

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;
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...