JavaScript 如何停止浏览器的后退按钮
在本文中,我们将讨论如何编写一个javascript函数,防止用户返回到上一页或上一个页面。有很多方法可以阻止浏览器的后退按钮,其中一种最流行并且适用于所有情况。您可以在第一个或上一页中添加代码,强制浏览器一遍又一遍地前进,因此当用户试图返回到上一页时,浏览器会再次带他返回到同样的页面。
可以通过编写自定义函数来实现:
示例1:
- 代码1: 将此文件保存为 Login.html ,用作第一个页面。
<!DOCTYPE html>
<html>
<head>
<title>
使用javascript阻止后退按钮
</title>
<style type="text/css">
body {
font-family:Arial;
color:green;
}
</style>
<script type="text/javascript">
window.history.forward();
function noBack() {
window.history.forward();
}
</script>
</head>
<body>
<h1>GeeksforGeeks</h2>
<p>
点击这里跳转到
<a href="b.html">
第二个页面的链接
</a>
</p>
</body>
</html>
- 代码2: 将此文件保存为 b.html ,用作第二个页面。
<!DOCTYPE html>
<html>
<head>
<title>
使用javascript阻止后退按钮
</title>
</head>
<body>
<h3>这是第二个页面</h3>
<p>
在此页面上,后退按钮功能被禁用。
</p>
</body>
</html>
- 输出:
示例2:
- 代码 1: 将此文件保存为 a.html 作为第一页。
<!DOCTYPE html>
<html>
<head>
<title>First Page</title>
<script type="text/javascript">
function preventBack() {
window.history.forward();
}
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>
</head>
<body>
<h3>This is first page</h3>
<hr />
<a href = "b.html">Goto second Page</a>
</body>
</html>
- 代码 2: 将此文件保存为 b.html 作为第二页。
<!DOCTYPE html>
<html>
<head>
<title>Second Page</title>
</head>
<body>
<h3>
Second Page - Back Button
is disabled here.
</h3>
<hr />
</body>
</html>
- 输出: