Jquery, Disable Browser Shortcut keys

17,053

Solution 1

If you have no limitation to use jQuery, this is a neat snippet that exactly do what you want:

var isCtrlHold = false;
var isShiftHold = false;
$(document).keyup(function (e) {
    if (e.which == 17) //17 is the code of Ctrl button
        isCtrlHold = false;
    if (e.which == 16) //16 is the code of Shift button
        isShiftHold = false;
});
$(document).keydown(function (e) {
    if (e.which == 17)
        isCtrlHold = true;
    if (e.which == 16)
        isShiftHold = true;
    ShortcutManager(e);
});
function ShortcutManager(e){
    //F1:
    if (e.which == 112) { //112 is the code of F1 button
        e.preventDefault(); //prevent browser from the default behavior
        alert("F1 is pressed");
    }
    //Ctrl+K:
    if (isCtrlHold && e.which == 75) { //75 is the code of K button
        e.preventDefault(); //prevent browser from the default behavior
        alert("Ctrl+K is pressed");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Press F1 or press Ctrl+K

Test it on JSFiddle.

You can find the javascript codes of all keys here: https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Solution 2

It seems that you cannot interfere with ctrl+key combinations that have special semantics for the browser (at least that seems to be the situation on chrome 34).

have a look at this fiddle demonstrating some ways to query keys and key combinations. note that upon pressing ctrl+n, the keydown handler still triggers the state transition (evidenced by inspecting the alerts upon the keystroke sequence ctrl+n, shift+n, shift+n).

However, I have not found a way to prevent the browser from claiming the keystrokes with meanings in the ui (which I believe is good, taking the user's perspective).

EDIT:

I found this SO answer adressing the issue on chrome (caveat: I haven't tested the solution wrt the current version of chrome).

Share:
17,053
Shivam Pandya
Author by

Shivam Pandya

Updated on June 04, 2022

Comments

  • Shivam Pandya
    Shivam Pandya 12 months

    I am trying to block some of browser shortcut keys for my projects like If user press F1 key then it should open a new page from project, but browse open its Help page. If I press Ctrl + N then it should open specific page but browser open new window.

    Here Is my code. (FIDDLE)

    $('body').keypress(function(event){
                if (event.keyCode == 17 && event.keyCode == 110)
                {
                    alert("New");   
                }
                else
                {
                    event.preventDefault(); 
                }
              });