How to handle Android back buttton with JavaScript?

1.1k views Asked by At

I'm making a WebView app for Android, using only HTML/CSS/JS, and i have to change the behaviour of the phone's back button in the navigation bar. (not the browser's back button.) How do i detect when the user clicks the back button of the phone and make my app do something? (WITH JAVASCRIPT.)

1

There are 1 answers

0
khangnd On

You need to override onBackPressed in the Android activity to call a JS function using webView.evaluateJavascript:

@Overide
public void onBackPressed() {
    webView.evaluateJavascript("window.doSomething()")
}

Then in your JS code, you can write the body of this doSomething() function. Make sure the function is exposed globally so that your Java code can access it like above.

For more advanced use cases, I'd recommend adopting Capacitorjs to your app, they have built a really robust system revolving the WebView techniques, and the migration process is rather simple and straightforward.