使用 Javascript 阻止 Android 后退按钮

Prevent Android Back Button Using Javascript

我有一个带有 CSS 和 Javascript 的简单 HTML 应用程序。我想阻止用户按下后退按钮。我已经使用 JavaScript 实现了它并且工作正常。我的问题是它在 Android 设备上不起作用,当用户在他们的设备上按下 "Hardware" 后退按钮时,他们会被重定向回上一页。

我找遍了 SO 但没有找到任何答案。谁能指出我正确的方向?

我没有使用 Cordova、ionic 等。这只是一个简单的 HTML 网页。

这是我遇到的答案:

history.pushState(null, null, window.top.location.pathname + window.top.location.search);
        window.addEventListener('popstate', (e) => {
            e.preventDefault();
            // Insert Your Logic Here, You Can Do Whatever You Want
            history.pushState(null, null, window.top.location.pathname + window.top.location.search);
        });

这是一个简单的解决方案:

history.pushState(null, null, location.href);
window.onpopstate = function () {
    history.go(1);
};

您还可以将 history.go(1); 部分替换为按下按钮时需要执行的任何代码。

详细说明@Farzad Soltani 的回答。这对我有用 android with e.preventDefault():

history.pushState(null, null, window.top.location.pathname + window.top.location.search);
        window.addEventListener('popstate', (e) => {
            e.preventDefault();
            history.pushState(null, null, window.top.location.pathname + window.top.location.search);
        });