我正在用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'
}
}
}
非常简单和干净的函数打破向后箭头,而不干扰页面之后。
好处:
Loads instantaneously and restores original hash, so the user isn't distracted by URL visibly changing.
The user can still exit by pressing back 10 times (that's a good thing), but not accidentally
No user interference like other solutions using onbeforeunload
It only runs once and doesn't interfere with further hash manipulations in case you use that to track state
Restores original hash, so almost invisible.
Uses setInterval, so it doesn't break slow browsers and always works.
Pure JavaScript, does not require HTML5 history, works everywhere.
Unobtrusive, simple, and plays well with other code.
Does not use unbeforeunload which interrupts user with modal dialog.
It just works without fuss.
注意:其他一些解决方案使用onbeforeunload。请不要为此目的使用onbeforeunload,当用户试图关闭窗口、点击反向箭头等时,onbeforeunload会弹出一个对话框。像onbeforeunload这样的情态动词通常只适用于很少的情况,比如当它们实际上在屏幕上做了更改并且没有保存它们时,不是为了这个目的。
工作原理
在页面加载时执行
保存您的原始散列(如果URL中有一个)。
依次追加#/noop/{1..10}到哈希
恢复原始哈希
就是这样。没有更多的混乱,没有后台事件监控,没有其他。
在一秒钟内使用它
要部署,只需在页面或JavaScript代码中添加这个:
<script>
/* Break back button */
window.onload = function(){
var i = 0;
var previous_hash = window.location.hash;
var x = setInterval(function(){
i++;
window.location.hash = "/noop/" + i;
if (i==10){
clearInterval(x);
window.location.hash = previous_hash;
}
}, 10);
}
</script>