How can I stop the browser back button using JavaScript?

前端 未结 30 3252
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:07

I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.

I have tried the following script, but it stops my timer.

30条回答
  •  离开以前
    2020-11-22 01:11

    This code will disable the back button for modern browsers which support the HTML5 History API. Under normal circumstances, pushing the back button goes back one step, to the previous page. If you use history.pushState(), you start adding extra sub-steps to the current page. The way it works is, if you were to use history.pushState() three times, then start pushing the back button, the first three times it would navigate back in these sub-steps, and then the fourth time it would go back to the previous page.

    If you combine this behaviour with an event listener on the popstate event, you can essentially set up an infinite loop of sub-states. So, you load the page, push a sub-state, then hit the back button, which pops a sub-state and also pushes another one, so if you push the back button again it will never run out of sub-states to push. If you feel that it's necessary to disable the back button, this will get you there.

    history.pushState(null, null, 'no-back-button');
    window.addEventListener('popstate', function(event) {
      history.pushState(null, null, 'no-back-button');
    });
    

提交回复
热议问题