我正在用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值中获取考试的持续时间。计时器随之启动,但当我输入禁用后退按钮的代码时,它就停止了。我有什么问题?
This code will disable the back button for modern browsers which support the HTML5 History API. Under normal circumstances, pushing the back button goes back one step, to the previous page. If you use history.pushState(), you start adding extra sub-steps to the current page. The way it works is, if you were to use history.pushState() three times, then start pushing the back button, the first three times it would navigate back in these sub-steps, and then the fourth time it would go back to the previous page.
如果您将此行为与popstate事件上的事件侦听器结合在一起,您实际上可以建立一个无限循环的子状态。因此,您加载页面,按下一个子状态,然后点击返回按钮,弹出一个子状态,并按下另一个子状态,因此,如果您再次按下返回按钮,它将永远不会没有子状态可按。如果你觉得有必要禁用后退按钮,这将使你达到目的。
history.pushState(null, null, 'no-back-button');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'no-back-button');
});
这里的一些解决方案不会阻止回退事件的发生——它们让回退事件发生(浏览器内存中关于页面的数据丢失),然后它们播放一个向前事件,试图隐藏回退事件刚刚发生的事实。如果页面处于暂时状态,则该方法将不成功。
我为React写了这个解决方案(当React路由器不被使用时),它是基于vrfvr的答案。
它将真正阻止后退按钮做任何事情,除非用户确认弹出:
const onHashChange = useCallback(() => {
const confirm = window.confirm(
'Warning - going back will cause you to loose unsaved data. Really go back?',
);
window.removeEventListener('hashchange', onHashChange);
if (confirm) {
setTimeout(() => {
window.history.go(-1);
}, 1);
} else {
window.location.hash = 'no-back';
setTimeout(() => {
window.addEventListener('hashchange', onHashChange);
}, 1);
}
}, []);
useEffect(() => {
window.location.hash = 'no-back';
setTimeout(() => {
window.addEventListener('hashchange', onHashChange);
}, 1);
return () => {
window.removeEventListener('hashchange', onHashChange);
};
}, []);