7

I have a simple HTML app with CSS and Javascript. I want to prevent the users from pressing the back button. I have achieved it using JavaScript and it works fine. My problem is that it doesn't work on Android devices, and when users press the "Hardware" back button on their devices, they get redirected back to the previous page.

I've gone all over SO but haven't found any answers. Could anyone point me in the right direction?

I'm not using Cordova, ionic, etc. It's just a simple HTML web page.

Farzad Soltani
  • 377
  • 7
  • 19

4 Answers4

6

This is the answer I came across :

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
  • 377
  • 7
  • 19
3

To elaborate on @Farzad Soltani's answer. This worked for me on 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);
        });
Luke
  • 22,826
  • 31
  • 110
  • 193
1

Here is a Simple solution :

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

You can also replace the history.go(1); part with any code that needs to be executed when the button is pressed.

Steev James
  • 2,396
  • 4
  • 18
  • 30
-2

If your idea to prevent the back action because you opened a modal you can do this. If not you can adapt.

Add this function to a script in index.html

function AddModalToHistory(url) {
        window.history.pushState("SaraivaForm.Client", "Modal", url);
    }

Inject JsRuntime on Blazor component

@inject IJSRuntime JsRuntime

Call from code once the modal is opened

protected override async Task OnInitializedAsync()
{
    await JsRuntime.InvokeAsync<string>("AddModalToHistory");
}
Ricardo Araújo
  • 191
  • 1
  • 2
  • 10