禁用浏览器后退按钮这个问题,困扰了我很长时间。现在终于得到解决,和大家一起分享。若有不妥的地方,欢迎大家指正,谢谢。
一,禁止后退到本页面
这个问题比较简单,只要在本页面用
window.history.forward(-1);
一句。问题就OK了。简单吧?
二,禁止后退出本页面
什么先不说,给出源码自己看看。本人已验证。
页面一的源码:
<html>
<head>
<META Http-Equiv="Cache-Control" Content="no-cache">
<META Http-Equiv="Pragma" Content="no-cache">
<META Http-Equiv="Expires" Content="0">
<title>next page</title>
<script type = "text/javascript">
function changeHashOnLoad() {
// 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' || location.hash == '') {
if ( history_api ) history.pushState(null, '', '#stay')
else location.hash = '#stay'
}
}
} else if(location.hash == '#stay') {
if ( history_api ) history.pushState(null, '', '#no-back')
else location.hash = '#no-back'
window.onhashchange = function() {
// User tried to go back; warn user, rinse and repeat
if ( location.hash == '#no-back' || location.hash == '') {
if ( history_api ) history.pushState(null, '', '#stay')
else location.hash = '#stay'
}
}
}
}
</script>
</head>
<body οnlοad="changeHashOnLoad()">
<h1>next page</h1>
</body>
</html>
页面二的源码:
<html>
<head>
<META Http-Equiv="Cache-Control" Content="no-cache">
<META Http-Equiv="Pragma" Content="no-cache">
<META Http-Equiv="Expires" Content="0">
<title>before page</title>
</head>
<body>
<a href="next.html#no-back">You can't go back from the next page</a>
</body>
</html>
上面只是一个例子。只要在禁用页面一的时候把参数#no-back传给页面一,页面一的后退按钮在本页就不能后退了。
欢迎和大家探讨。