Prevent user pressing f5 button in pop up window

2.1k views Asked by At

I want to prevent users from pressing the F5 button because of running exam test in my project.

If I use a normal browser window, my code works fine, but now I want to use it in a popup windows - in the popup windows my code is not working. My code is:

document.onkeydown=function(e) {
    var event = window.event || e;
    if (event.keyCode == 116) {
        event.keyCode = 0;
        alert("This action is not allowed");
        return false;
    }
}
3

There are 3 answers

0
idipous On

If what you are looking for is to supress refreshing of your web page then you should ask why you need this. If it is so as not to resend the data already sent then you should use a different php file for doing the proccessing of your data and a different to display them to your user. This way you can check whether anything is awry and redirect him accordingly.

If you for some specific reason trully need to prevent refreshing through F5 then what Cobra_Fast suggested e.preventDefault(); should do the trick.

1
Amith On

try this

myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.focus();
myWindow.onkeydown=function(e) {
    var event = window.event || e;
    if (event.keyCode == 116) {
        event.preventDefault();
        alert("This action is not allowed");
    }
}
0
Alex On
document.onkeydown = function(e){
    var event = (window.event || e);
    if(event.keyCode==116){
        event.preventDefault();
        alert("This action is not allowed");
    }
}

You don't need this part of code: event.keyCode = 0; - changing keyCode after key is pressed won't affect anything.