Asked
Updated
Viewed
41.5k times

On my website, I would like to disable the browser's back button and key so that a user cannot go back to the previous page.

I was taking an online exam in which a message box was displayed when the BACK button was clicked. I don't know if the coding is done in some other language but the message box popped up very quickly as soon I pressed the BACK button.

Additionally, I would like to disable the F5 key to prevent a user from refreshing their browser, perhaps they can be both done in a similar manner using JavaScript?

add a comment
0

2 Answers

  • Votes
  • Oldest
  • Latest
Answered
Updated

To disable the back button and another key such as F5 you can use the following code:

<script>
window.history.forward(1); // Disable Back Button
document.attachEvent("onkeydown", my_onkeydown_handler); // Disable F5 Key

function my_onkeydown_handler() {
    switch (event.keyCode) {
        case 116 : // 'F5'
        event.returnValue = false;
        event.keyCode = 0;
        window.status = "We have disabled F5";
        break;
    }
}
</script>
add a comment
1
Answered
Updated

Disabling the back button is easy. You need your webpage A to go to a temporary page B that does a JavaScript forward to C. When the user is on page C and hits his back button, it goes back to B, which then goes forward again to C.

The second time through, you could always go to D instead of to C, your choice.

Make some experiments, but it is possible. Also, you might want to investigate using a form POST and JavaScript Submit to disable the back button.

add a comment
0