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


当前回答

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

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

其他回答

<script src="~/main.js" type="text/javascript"></script>

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

    function noBack() {
        window.history.forward();
    }
</script>

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

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

我有这个问题与React(类组件)。

我很容易就解决了:

componentDidMount() {
    window.addEventListener("popstate", e => {
        this.props.history.goForward();
    }
}

我已经从react-router-dom中使用了HashRouter。

它基本上是分配窗口的“onbeforeunload”事件以及正在进行的文档“mouseenter”/“mouseleave”事件,因此警报只在单击超出文档范围时触发(然后可以是浏览器的后退或前进按钮)

美元(文档)。On ('mouseenter',函数(e) { 窗口。Onbeforeunload = null; } ); 美元(文档)。On ('mouseleave',函数(e) { 窗口。onbeforeunload = function(){返回"你的工作将会丢失";}; } );

限制浏览器返回事件:

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