I am doing online quiz app in php. I want to restrict user while going back in exam. I have tried following script but it stops my timer. What should I do please suggest me. I have included source code. The timer is stored in cdtimer.js
<script type="text/javascript">
window.history.forward();
function noBack()
{
window.history.forward();
}
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">
I have exam timer which takes duration of exam from mysql db and starts timer accordingly it stops when I put code for disabling back button. what will be the problem.
Very simple and clean function to break the back arrow without interfering with the page afterward.
Benefits:
onbeforeunload
setInterval
so it doesn't break slow browsers and always works.unbeforeunload
which interrupts user with modal dialog.Note: some of the other solutions use
onbeforeunload
. Please do not useonbeforeunload
for this purpose, which pops up a dialog whenever users try to close the window, hit backarrow, etc. Modals likeonbeforeunload
are usually only appropriate in rare circumstances, such as when they've actually made changes on screen and haven't saved them, not for this purpose.How It Works
That's it. No further messing around, no background event monitoring, nothing else.
Use It In One Second
To deploy, just add this anywhere on your page or in your JS:
This article on jordanhollinger.com is the best option I feel. Similar to Razor's answer but a bit clearer. Code below; full credits to Jordan Hollinger:
Page before:
Page of no return's JavaScript:
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.This is the way I could it accomplish it. Weirdly changing the window.location didn't worked out fine in chrome and safari. Happens that the location.hash doesn't create an entry in the history for chrome and safari. So you will have to use the pushstate. This is working for me in all browsers.
This seems to have worked for us in disabling the back button on the browser, as well as the backspace button taking you back.