How can I stop the browser back button using JavaScript?

前端 未结 30 3300
没有蜡笔的小新
没有蜡笔的小新 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:05

    It is generally a bad idea overriding the default behavior of the web browser. A client-side script does not have the sufficient privilege to do this for security reasons.

    There are a few similar questions asked as well,

    • How can I prevent the backspace key from navigating back?

    • How can I prevent the browser's default history back action for the backspace button with JavaScript?

    You can-not actually disable the browser back button. However, you can do magic using your logic to prevent the user from navigating back which will create an impression like it is disabled. Here is how - check out the following snippet.

    (function (global) {
    
        if(typeof (global) === "undefined") {
            throw new Error("window is undefined");
        }
    
        var _hash = "!";
        var noBackPlease = function () {
            global.location.href += "#";
    
            // Making sure we have the fruit available for juice (^__^)
            global.setTimeout(function () {
                global.location.href += "!";
            }, 50);
        };
    
        global.onhashchange = function () {
            if (global.location.hash !== _hash) {
                global.location.hash = _hash;
            }
        };
    
        global.onload = function () {
            noBackPlease();
    
            // Disables backspace on page except on input fields and textarea..
            document.body.onkeydown = function (e) {
                var elm = e.target.nodeName.toLowerCase();
                if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
                    e.preventDefault();
                }
                // Stopping the event bubbling up the DOM tree...
                e.stopPropagation();
            };
        }
    })(window);
    

    This is in pure JavaScript, so it would work in most of the browsers. It would also disable the backspace key, but that key will work normally inside input fields and textarea.

    Recommended Setup:

    Place this snippet in a separate script and include it on a page where you want this behavior. In the current setup it will execute the onload event of the DOM which is the ideal entry point for this code.

    Working DEMO!

    It was tested and verified in the following browsers,

    • Chrome.
    • Firefox.
    • Internet Explorer (8-11) and Edge.
    • Safari.

提交回复
热议问题