如何使用JavaScript停止浏览器的后退按钮
停止浏览器的后退按钮意味着防止用户返回到之前的页面。有时,出于安全目的,我们需要阻止用户返回当前页面之前的页面。
例如,大多数银行网站在你正在使用在线银行进行某些交易时,不允许你返回。因为如果用户在交易中途返回,可能会造成一些问题。所以只允许你完成交易或取消交易并重新开始。
这里,我们将学习使用JavaScript阻止用户从当前网页返回到之前网页的各种方法。在本教程中,我们将学习使用JavaScript或jQuery停止浏览器的后退按钮。
使用window.history.forward()方法
window.history.forward()方法允许我们将用户重定向到之前的URL。window对象以堆栈格式存储位置对象。因此,history对象的forward()方法查找最后一个位置并将用户重定向到该位置对象的URL。
语法
用户可以按照以下语法使用history对象的forward()方法。
window.history.forward();
在上面的语法中,window指的是全局对象,每个网页都包含window对象。
示例1
在下面的示例中,我们使用HTML的标签创建了一个链接,将用户发送到TutorialsPoint网站的首页。在JavaScript中,我们只是添加了window.history.forward()方法。
现在,每当用户从当前网页转到TutorialsPoint网站的首页时,他们将无法返回到此页面。
<html>
<body>
<h2>Preventing the browser's back button using the <i> window.history.forward() </i> method. </h2>
<h3>Click the below link. </h3>
<a href = "https://www.tutorialspoint.com/index.htm"> tutorialspoint</a>
<script>
window.history.forward();
</script>
</body>
</html>
示例2
在下面的示例中,我们使用了setTimeOut()函数在一定时间后将用户重定向到上一个页面。在setTimeOut()函数中,我们在1秒后调用window.history.forward()方法。
因此,在输出中,用户可以观察到每当他们从TutorialsPoint网站的首页返回到当前页面时,它将在1秒后再次重定向。
<html>
<body>
<h2>Preventing the browser's back button using the <i> window.history.forward() </i> method. </h2>
<h3>Click the below link. </h3>
<a href = "https://www.tutorialspoint.com/index.htm"> tutorialspoint </a>
<script>
setTimeout(() => { window.history.forward() }, 1000);
</script>
</body>
</html>
使用window.history.go()方法
window.history.go()方法将用户重定向到上一个位置的URL。
语法
用户可以按照以下语法使用window.history.go()方法来阻止浏览器的返回按钮。
<body onload = "stopBack();"></body>
<script>
function stopBack() {
window.history.go(1);
}
</script>
在上面的语法中,我们向HTML的
元素添加了onload属性,并调用了stopBack()函数。示例3
在下面的示例中,我们使用window.history.go()方法将用户重定向到上一页。每当网页加载时,它将调用stopBack函数,并从当前页将用户重定向到上一页,通过这种方式,我们可以停止浏览器的后退按钮。
<html>
<body onload="stopBack();">
<h2>Preventing the browser's back button using the <i>window.history.go() </i> method.</h2>
<h3>Click the below link. </h3>
<a href = "https://www.tutorialspoint.com/index.htm"> tutorialspoint</a>
<div id = "output"> </div>
<script>
var output = document.getElementById('output');
function stopBack() {
window.history.go(1);
}
</script>
</body>
</html>
我们学会了防止用户返回到特定的网页。我们使用了window.history.forward() 和 window.history.go() 方法。