How can I stop the browser back button using JavaScript?

Sawant Akshay picture Sawant Akshay · Sep 12, 2012 · Viewed 553.3k times · Source

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.

What should I do?

The timer is stored in file 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 the exam timer which takes a duration for the exam from a MySQL value. The timer starts accordingly, but it stops when I put the code in for disabling the back button. What is my problem?

Answer

ColinE picture ColinE · Sep 12, 2012

There are numerous reasons why disabling the back button will not really work. Your best bet is to warn the user:

window.onbeforeunload = function() { return "Your work will be lost."; };

This page does list a number of ways you could try to disable the back button, but none are guaranteed:

http://www.irt.org/script/311.htm