How can I stop the browser back button using JavaScript?

前端 未结 30 4021
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  猫巷女王i
    2020-11-22 01:04

    I believe the perfect yet solution is actually pretty straightforward, which I used for many years now.

    It's basically assigning the window's "onbeforeunload" event along with the ongoing document 'mouseenter' / 'mouseleave' events so the alert only triggers when clicks are outside the document scope (which then could be either the back or forward button of the browser)

    $(document).on('mouseenter', function(e) { 
            window.onbeforeunload = null; 
        }
    );
    
    $(document).on('mouseleave', function(e) { 
            window.onbeforeunload = function() { return "You work will be lost."; };
        }
    );
    

提交回复
热议问题