我正在用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'
}
}
}
这是我为谷歌查询“禁用后退按钮”获得的第一个命中。我的用例与最初发布的问题略有不同。我需要“禁用后退按钮”的用户已登录的一个安全的网站(即防止一个用户从注销,然后另一个用户能够从以前的用户通过点击后退按钮查看信息)。
简而言之,这里的目标是防止用户在登录的用户注销后看到应用程序页面。
这可以通过向经过身份验证的应用程序的页面中添加如下所示的代码来实现。
下面是使用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>
在Chrome 79中,被点赞最多的答案没有一个对我有效。看起来Chrome在75版之后改变了后退按钮的行为。在这里看到的:
https://support.google.com/chrome/thread/8721521?hl=en
然而,在谷歌的帖子中,Azrulmukmin Azmi在最后提供的答案确实起作用了。这是他的解。
<script>
history.pushState(null, document.title, location.href);
history.back();
history.forward();
window.onpopstate = function () {
history.go(1);
};
</script>
Chrome的问题是它不会触发onpopstate事件
除非你做出浏览器动作(即调用history.back)。这就是为什么
我已经将这些添加到脚本中。
我不完全明白他写了什么,但显然现在需要一个额外的history.back() / history.forward()来阻止Chrome 75+中的返回。
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
此JavaScript代码不允许任何用户返回(适用于Chrome, Firefox, Internet Explorer和Edge)。