how to stop browser back button using javascript

2018-12-31 04:06发布

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.

21条回答
怪性笑人.
2楼-- · 2018-12-31 04:42
<html>
<head>
    <title>Disable Back Button in Browser - Online Demo</title>
    <style type="text/css">
        body, input {
            font-family: Calibri, Arial;
        }
    </style>
    <script type="text/javascript">
        window.history.forward();
        function noBack() {
            window.history.forward();
        }
    </script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <H2>Demo</H2>
    <p>This page contains the code to avoid Back button.</p>
    <p>Click here to Goto <a href="noback.html">NoBack Page</a></p>
</body>
</html>
查看更多
若你有天会懂
3楼-- · 2018-12-31 04:43

Try this to prevent backspace button in IE which by default act as "Back":

<script language="JavaScript">
$(document).ready(function() {
$(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;


    if (event.keyCode === 8 ) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && 
             (
                 d.type.toUpperCase() === 'TEXT' ||
                 d.type.toUpperCase() === 'PASSWORD' || 
                 d.type.toUpperCase() === 'FILE' || 
                 d.type.toUpperCase() === 'EMAIL' || 
                 d.type.toUpperCase() === 'SEARCH' || 
                 d.type.toUpperCase() === 'DATE' )
             ) || 
             d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else {

            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }

    try {
        document.addEventListener('keydown', function (e) {
               if ((e.keyCode === 13)){
                  // alert('Enter keydown');
                   e.stopPropagation();
                   e.preventDefault();
               }



           }, true);
        } catch (err) {}
    });
});
</script>
查看更多
千与千寻千般痛.
4楼-- · 2018-12-31 04:45

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

There are few similar questions asked as well,

You can-not actually disable browser back button. However you can do magic using your logic to prevent 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 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 backspace key but 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 current setup it will execute onload event of DOM which is the ideal entry point for this code.

Working DEMO!

Tested and verified in following browsers,

  • Chrome.
  • Firefox.
  • IE (8-11) and Edge.
  • Safari.
查看更多
其实,你不懂
5楼-- · 2018-12-31 04:45
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

This javascript does not allow any user to go back (works in Chrome, FF, IE, Edge)

查看更多
怪性笑人.
6楼-- · 2018-12-31 04:46
<script>
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="no-back-button";}
</script> 
查看更多
刘海飞了
7楼-- · 2018-12-31 04:46

    history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1);
    };

查看更多
登录 后发表回答