Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 757
Farzad Soltani Avatar asked Jun 22 '26 21:06

Farzad Soltani


1 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);
        });
like image 100
Farzad Soltani Avatar answered Jun 25 '26 11:06

Farzad Soltani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!