8

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.

2
  • have you found the solution? Commented Aug 3, 2018 at 9:13
  • @paulcheung yes, I added the answer Commented Aug 5, 2018 at 8:40

4 Answers 4

7

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);
        });
Sign up to request clarification or add additional context in comments.

2 Comments

it helped. @Farzad Soltani.
This only worked for me when I put the event parameter in there and put e.preventDefault(); before the history.pushState
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);
        });

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.