阻止用户点击浏览器的后退按钮

-2 javascript browser jquery cross-browser microsoft-edge

我想禁用浏览器的后退按钮。我尝试过一些 javascript 代码来实现相同的功能。但这些代码并没有满足我的要求。它可以在 Firefox 中运行,但不能在 Chrome 和 Edge 中运行。有时这三个都可以工作,但随机工作和不工作。

任何人都可以与我分享该脚本,该脚本可以在所有浏览器中禁用后退按钮,而不会出现随机行为等缺陷。

这里我展示了一些我尝试过的脚本

history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();

history.pushState(null, null, location.href);
history.back();
history.forward();
window.onpopstate = function () { history.go(1); };
Run Code Online (Sandbox Code Playgroud)

Yu *_*hou 6

可以参考下面的代码。我在 Edge、Chrome 和 Firefox 中测试了代码示例,效果很好。

将此文件另存为首页的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>
    <a href="b.html">Goto second Page</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

将此文件另存为第二页的b.html :

<!DOCTYPE html>
<html>
<head>
    <title>
        Blocking Back Button using javascript
    </title>
</head>
<body>
    <h3>This is second page</h3>
    <p>
        On this page, back button functionality is disabled.
    </p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

运行 a.html 并单击导航到 b.html。然后单击 b.html 上的浏览​​器后退按钮,它不会导航到 a.html。