Search code examples
javascriptandroidhtmlandroid-buttononbackpressed

Prevent Android Back Button Using Javascript


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.


Solution

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