Link to home
Start Free TrialLog in
Avatar of paku
paku

asked on

How to disable keyboard F5 button ?

Hi

I want to disable the F5 , Ctrl+R or Ctrl+ N, Backspace etc buttons. Actually i am developing Online test module and the purpose is the end user should not be able to refresh or open a new window in between the test. Here is the code which i have got from net but its not working can anybody help me ...

<html>
<head>
<script type="text/JavaScript">

       function showDown(evt) {
      
        evt = (evt) ? evt : ((event) ? event : null);
        if (evt) {
            alert(evt.keyCode);
            if (window.event.keyCode == 8 && (window.event.srcElement.type != "text" && window.event.srcElement.type != "textarea" && window.event.srcElement.type != "password"))
                  {
                // When backspace is pressed but not in form element
                        alert("When backspace is pressed but not in form element");
                cancelKey(evt);
            }
            else if (window.event.keyCode == 20) {
                // When F5 is pressed
                        alert("When F5 is pressed")
                cancelKey(evt);
            }
            else if (window.event.ctrlKey && (window.event.keyCode == 78 || window.event.keyCode == 82)) {
                // When ctrl is pressed with R or N
                        alert("When ctrl is pressed with R or N");
                cancelKey(evt);
            }
        }
    }

    function cancelKey(evt) {
      alert("Inside cancelKey(evt)");
        if (evt.preventDefault) {
            evt.preventDefault();
            return false;
        }
        else {
            evt.keyCode = 0;
            evt.returnValue = false;
        }
    }


</script>

</head>

<body onKeyPress = "showDown(winodw.event)">
<FORM ACTION="">
</FORM>
</body>
</html>


Prakash.
Avatar of GwynforWeb
GwynforWeb
Flag of Canada image

This not going to happen, not all key presses can be detected. It is part of the security idea of browsers and the internet.
Avatar of sajuks
sajuks

Try changing <body onKeyPress = "showDown(winodw.event)">
to
<body onkeyup = "showDown(window.event)">

also you'd a spelling mistake its window and not winodw
agree with gfw that this is going to fail in other browsers like netscape,opera
Avatar of paku

ASKER

Is there any other way to achive this functionality... GwynforWeb.

The client browser wont allow you to take control of the browser thru javascript coding.
Check http://tech.irt.org/articles/js195/ for key board trapping events.
paku, I gather you want to stop reresh. I do know how to do this, but could you tell me why you need to do this?  (going to bed in 5mins)
ASKER CERTIFIED SOLUTION
Avatar of GwynforWeb
GwynforWeb
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial