使用Javascript禁用Android返回按钮

7
我有一个带有CSS和Javascript的简单HTML应用程序。我想防止用户按返回按钮。我已经使用JavaScript实现了它,并且运行良好。我的问题是它在Android设备上无法正常工作,当用户按下他们设备上的"硬件"返回按钮时,他们会被重定向回到前一页。
我已经在SO上搜索过了,但没有找到任何答案。有人能指点我正确的方向吗?
我没有使用Cordova、Ionic等,只是一个简单的HTML网页。

你找到解决方案了吗? - paul cheung
@paulcheung 是的,我添加了答案。 - Farzad Soltani
4个回答

6

我找到的答案是:

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);
        });

它有所帮助。@Farzad Soltani。 - paul cheung
只有当我将事件参数放在那里并在history.pushState之前放置e.preventDefault();时,这才对我起作用。 - Luke

3

继@Farzad Soltani的答案后,我想进一步说明。这对我在安卓设备上使用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);
        });

1

以下是一个简单的解决方案:

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

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


-2
如果您的想法是防止因为打开模态框而返回操作,您可以这样做。如果不是,您可以进行调整。
将此函数添加到 index.html 中的脚本中。
function AddModalToHistory(url) {
        window.history.pushState("SaraivaForm.Client", "Modal", url);
    }

在 Blazor 组件中注入 JsRuntime

@inject IJSRuntime JsRuntime

模态框打开后从代码中调用

protected override async Task OnInitializedAsync()
{
    await JsRuntime.InvokeAsync<string>("AddModalToHistory");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接