I want to disable F5 key in my web application. I am using the following code:
<html>
<head>
<script type="text/javascript">
window.onkeydown=function(e) {
if (e.keyCode === 116 ) {
alert("This action is not allowed");
e.keyCode = 0;
e.returnValue = false;
return false;
}
}
</script>
</head>
<body>
<p> F5 Test IE8</p>
</body>
</html>
The above code works fine in Chrome but in IE8 it is not working. On pressing F5 the page gets refreshed on IE8. I have tried using e.preventDefault(), but nothing works. Any help??
I want to disable F5 key in my web application. I am using the following code:
<html>
<head>
<script type="text/javascript">
window.onkeydown=function(e) {
if (e.keyCode === 116 ) {
alert("This action is not allowed");
e.keyCode = 0;
e.returnValue = false;
return false;
}
}
</script>
</head>
<body>
<p> F5 Test IE8</p>
</body>
</html>
The above code works fine in Chrome but in IE8 it is not working. On pressing F5 the page gets refreshed on IE8. I have tried using e.preventDefault(), but nothing works. Any help??
Share Improve this question asked Apr 19, 2012 at 5:22 Himanshu SaraswatHimanshu Saraswat 931 gold badge2 silver badges5 bronze badges 5- 9 For what purpose? They could also use Ctrl/Cmd + R or press the refresh button. – Theron Luhn Commented Apr 19, 2012 at 5:24
- I think another(may be better) option is to check if user is navigating away from page (example: refresh) and ask for confirmation. – Shoban Commented Apr 19, 2012 at 5:29
- 4 Don't tamper with default browser functionality. – Ateş Göral Commented Apr 19, 2012 at 5:30
- This happens at the browser level, not the DOM level. Basically, you can't do that, even if there were any possible good reason to do so. – John Green Commented Apr 19, 2012 at 5:32
- 1 I agree with you John, but that's how the project's requirement is – Himanshu Saraswat Commented Apr 19, 2012 at 15:00
2 Answers
Reset to default 4Try next code:
<html>
<head>
<script type="text/javascript">
document.onkeydown=function(e) {
e=e||window.event;
if (e.keyCode === 116 ) {
e.keyCode = 0;
alert("This action is not allowed");
if(e.preventDefault)e.preventDefault();
else e.returnValue = false;
return false;
}
}
</script>
</head>
<body>
<p> F5 Test IE8</p>
</body>
</html>
- You must use
document
object instead ofwindow
object. In IE8window
object does not supportonkeydown
. - You must use
e=e||window.event;
code line because in IE8- when event registered aselement.on...
no parameter is received into event handler function (e
from your example isundefined
);
Tested in IE8, firefox and chrome:
document.onkeydown=function(e) {
var event = window.event || e;
if (event.keyCode == 116) {
event.keyCode = 0;
alert("This action is not allowed");
return false;
}
}
Also see this example.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744910314a4600509.html
评论列表(0条)