Search code examples
javascriptjqueryjquery-eventspreventdefault

How to restrict keyboard key events in web application?


I am doing the secured web application. My client requirement is to don't allow the application to refresh using the F5 .

Also to restrict events of the Esc , Backspace keys.

I am using the jQuery 1.9.1.

My code is given below.

I can get the alert, but if I press the F5 button my page gets refreshed. I don't know why?

BackSpace also going back to the previous page.

$(document).on('keydown' , function(event) {

    switch (event.keyCode) {

    case 116 : // 'F5'
    alert("116 :"+event.keyCode);
    event.preventDefault();
    event.returnValue = false;
    event.keyCode = 0;;
     break;  

    case 27: // 'Esc'

    alert("27 :"+event.keyCode);
    event.preventDefault();
    event.returnValue = false;
    break;

    case 08: // 'BackSpace'
    if (event.srcElement.tagName == "INPUT"
        || event.srcElement.tagName == "TEXTAREA") {
    } else {
        event.preventDefault();
        event.returnValue = false;
        event.keyCode = 0;  
    }
    break;

    }

});

Can any one point out me where I made a mistake ?


Solution

  • Look here. Try to enter something into input box and try 'f5', 'esc' and 'backspace' keys on frame. It works in jsFiddle under Mac Chrome browser, it should work on your browser also. When you preventing your event you should call stopProagation function. Moreover, when you calling srcElement you should call original events by event.originalEvent.srcElement because normalised jquery event doesn't contain srcElement property. In console it gives undefined property error. Also you have error like following event.keyCode = 0;*;*

    $(document).on('keydown' , function(event) {
    
        switch (event.keyCode) {
    
        case 116 : // 'F5'
        alert("116 :"+event.keyCode);
        event.preventDefault();
        event.stopPropagation();
                console.log('hello');
         break;  
    
        case 27: // 'Esc'
    
        alert("27 :"+event.keyCode);
        event.preventDefault();
        event.stopPropagation();
        break;
    
        case 08: // 'BackSpace'
        if (event.originalEvent.srcElement.tagName == "INPUT"
            || event.originalEvent.srcElement.tagName == "TEXTAREA") {
                alert("27 :"+event.keyCode);
        event.preventDefault();
        event.stopPropagation();
        } else {
        alert("27 :"+event.keyCode);
        event.preventDefault();
        event.stopPropagation(); 
        }
        break;
    
        }
    
    });