我正在用PHP做一个在线测试应用程序。我想限制用户在考试中返回。

我尝试了下面的脚本,但它停止了我的计时器。

我该怎么办?

定时器存储在cdtimer.js文件中。

<script type="text/javascript">
    window.history.forward();
    function noBack()
    {
        window.history.forward();
    }
</script>

<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">

我有一个考试计时器,它从一个MySQL值中获取考试的持续时间。计时器随之启动,但当我输入禁用后退按钮的代码时,它就停止了。我有什么问题?


当前回答

重写web浏览器的默认行为通常不是一个好主意。出于安全原因,客户端脚本没有足够的特权来执行此操作。

还有一些类似的问题,

如何防止退格键导航回? 我如何可以防止浏览器的默认历史后退动作退格按钮与JavaScript?

你不能禁用浏览器的后退按钮。然而,你可以使用你的逻辑来阻止用户返回,这将创造一个像它被禁用的印象。这是如何-检查以下片段。

(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);

这是纯JavaScript,所以它可以在大多数浏览器中工作。它也会禁用退格键,但该键将在输入字段和文本区域内正常工作。

建议设置:

将此片段放在单独的脚本中,并将其包含在需要此行为的页面上。在当前设置中,它将执行DOM的onload事件,这是这段代码的理想入口点。

工作演示!

它在以下浏览器中进行了测试和验证,

铬。 Firefox。 ie浏览器(8-11)和Edge。 Safari。

其他回答

这是我为谷歌查询“禁用后退按钮”获得的第一个命中。我的用例与最初发布的问题略有不同。我需要“禁用后退按钮”的用户已登录的一个安全的网站(即防止一个用户从注销,然后另一个用户能够从以前的用户通过点击后退按钮查看信息)。

简而言之,这里的目标是防止用户在登录的用户注销后看到应用程序页面。

这可以通过向经过身份验证的应用程序的页面中添加如下所示的代码来实现。

下面是使用Apache Shiro的完整示例:

https://github.com/NACHC-CAD/web-security-example/releases/tag/v2.0.0

<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE" />

<script>
    if(performance.navigation.type == 2){
        console.log("Doing reload");   
        location.reload(true);
        console.log("Done with reload");
    }
    console.log("Script loaded.")
</script>

这似乎在禁用浏览器上的后退按钮,以及退格键带你回到工作。

history.pushState(null, null, $(location).attr('href'));
window.addEventListener('popstate', function () {
    history.pushState(null, null, $(location).attr('href'));
});

尝试以下方法来防止ie浏览器中的退格键默认为“后退”:

<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>

这是另一种方法。我们可以添加简短的SessionStorage条件,而不是仅仅尝试避免Back按钮功能(它不可靠地工作)。

假设我们有三个不同的页面(page1、page2和page3)。在每个页面上,我们都有一个链接,点击进入下一个页面,我们不希望用户能够回到上一页。

在第一个页面(page1.html),我们创建了一个SI (sessionStorage Item)与一个虚拟的“prev”代码和另一个与“page1”代码(SI“now”):

  PAGE 1  <button onclick="goto()">PAGE 2</button>

  -------------------

  let thispage = '1' // Or 123456 if preferred or make sense

  // You can replace this fixed 'thispage' value on each page with a script counting the clicks
  // or any other way to increase its value, i.e., thispage++
  // or what you want, even counting the url.length (lol)

  sessionStorage.setItem('prev', '0') // Dummy code
  sessionStorage.setItem('now', thispage)

  // You can here make this page unreachable with page2/page3 SI same conditions

  function goto(){
      window.location = "page2.html"
  }

在page2.html上,我们使用通常的NoBack脚本(如果它有效的话),只在来自page1时更新si:

  PAGE 2  <button onclick="goto()">PAGE 3</button>

  -------------------

  // If it works, let it work :-)

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

  // else

  let thispage = '2' // 456789
  let thisprev = sessionStorage.getItem('now')
  if(sessionStorage.getItem('prev')==thispage) {
      console.log('USER is back on PAGE 2')
      setTimeout(function() { goto() }, 1000); // Remove log + setTimeout
  }
  if(thisprev !== thispage) {
      if(thisprev < thispage) {
          console.log('USER is coming from PAGE 1')
          sessionStorage.setItem('prev', thisprev)
          sessionStorage.setItem('now', thispage)
      }
      else {
          console.log('USER try to reload this page')
          setTimeout(function() { goto() }, 1000);
      }
  }

  function goto(){
      window.location = "page3.html"
  }

在page3.html上:

  PAGE 3  <button onclick="goto()">BACK TO PAGE 1</button>

  -------------------

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

  let thispage = '3' // 999999
  let thisprev = sessionStorage.getItem('now')
  if(sessionStorage.getItem('prev') == thispage) {
      goto()
  }
  if(thisprev !== thispage) {
      if(thisprev < thispage) {
          sessionStorage.setItem('prev', thisprev)
          sessionStorage.setItem('now', thispage)
      }
      else {
          goto()
      }
  }
  function goto(){
      window.location = "page1.html" // Reinit test
  }

这样做的好处是,即使用户手动重新加载前一个页面(如果他有时间查看并记住URL),它仍然可以工作。它没有在所有设备上进行测试,但似乎在Firefox + Chrome + Edge Windows 10和Firefox + Chrome在OS X上运行良好。

这段代码是完整的javascript。 把这个放在你的主页或者其他你需要的地方当有人返回时,它会把他们带到他们之前所在的页面。

<script type="text/javascript"> 
        function preventBack() { 
            window.history.forward();  
        } 
          
        setTimeout("preventBack()", 0); 
          
        window.onunload = function () { null }; 
    </script>