How can I stop the browser back button using JavaScript?

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

    //"use strict";
    function stopBackSpace(e) {
        var ev = e || window.event;
        var obj = ev.target || ev.srcElement;
        var t = obj.type || obj.getAttribute('type');
    
        var vReadOnly = obj.getAttribute('readonly');
        var vEnabled = obj.getAttribute('enabled');
        // null
        vReadOnly = (vReadOnly == null) ? false : vReadOnly;
        vEnabled = (vEnabled == null) ? true : vEnabled;
        // when click Backspace,judge the type of obj.
    
        var flag1 = ((t == 'password' || t == 'text' || t == 'textarea') && ((vReadOnly == true || vReadOnly == 'readonly') || vEnabled != true)) ? true : false;
    
        var flag2 = (t != 'password' && t != 'text' && t != 'textarea') ? true : false;
    
        if (flag2) {
            e.keyCode = 0;
            e.cancelBubble = true;
            return false;
        }
        if (flag1) {
            e.keyCode = 0;
            e.cancelBubble = true;
            return false;
        }
    }
    if (typeof($) == 'function') {
        $(function() {
            $(document).keydown(function(e) {
                if (e.keyCode == 8) {
                    return stopBackSpace(e);
                }
            });
        });
    } else {
        document.onkeydown = stopBackSpace;
    }
    

提交回复
热议问题