我正在用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值中获取考试的持续时间。计时器随之启动,但当我输入禁用后退按钮的代码时,它就停止了。我有什么问题?


当前回答

我觉得jordanhollinger.com上的这篇文章是最好的选择。与Razor的答案相似,但更清楚一些。下面的代码;全部归功于Jordan Hollinger:

页面:

<a href="/page-of-no-return.htm#no-back>You can't go back from the next page</a>

no return的JavaScript页面:

// It works without the History API, but will clutter up the history
var history_api = typeof history.pushState !== 'undefined'

// The previous page asks that it not be returned to
if ( location.hash == '#no-back' ) {
  // Push "#no-back" onto the history, making it the most recent "page"
  if ( history_api ) history.pushState(null, '', '#stay')
  else location.hash = '#stay'

  // When the back button is pressed, it will harmlessly change the url
  // hash from "#stay" to "#no-back", which triggers this function
  window.onhashchange = function() {
    // User tried to go back; warn user, rinse and repeat
    if ( location.hash == '#no-back' ) {
      alert("You shall not pass!")
      if ( history_api ) history.pushState(null, '', '#stay')
      else location.hash = '#stay'
    }
  }
}

其他回答

轻松尝试一下:

history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});

只需设置location.hash="Something"。在按下返回按钮时,散列将从URL中删除,但页面不会返回。

此方法用于防止意外返回,但出于安全性考虑,您应该设计用于防止应答的后端。

只需立即运行代码片段并尝试返回 历史。pushState(null, null, window.location.href); history.back (); 窗口。Onpopstate = () => history.forward();

有很多原因可以解释为什么禁用后退按钮实际上不起作用。最好的办法是警告用户:

window.onbeforeunload = function() { return "Your work will be lost."; };

本页确实列出了一些禁用后退按钮的方法,但都不保证:

http://www.irt.org/script/311.htm

在现代浏览器中,这似乎是可行的:

// https://developer.mozilla.org/en-US/docs/Web/API/History_API
let popHandler = () => {
  if (confirm('Go back?')) {
    window.history.back() 
  } else {
    window.history.forward()
    setTimeout(() => {
      window.addEventListener('popstate', popHandler, {once: true})
    }, 50) // delay needed since the above is an async operation for some reason
  }
}
window.addEventListener('popstate', popHandler, {once: true})
window.history.pushState(null,null,null)