Prevent Android Back Button Using Javascript

Viewed 2844

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.

3 Answers

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

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

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.

Related