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.)
Asked
Active
Viewed 885 times
2
-
1try the suggested answers here - [https://stackoverflow.com/questions/47092384/use-javascript-jquery-detect-android-back-button/47092587](https://stackoverflow.com/questions/47092384/use-javascript-jquery-detect-android-back-button/47092587), [Detect use of Android back button using JavaScript](https://stackoverflow.com/questions/20373849/detect-use-of-android-back-button-using-javascript). – PJA Sep 09 '20 at 13:17
-
"onpopstate" and "onhashchange" events are not working, and the other answer is Java code. – Ercan Tomaç Sep 09 '20 at 13:31
1 Answers
0
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.

khangnd
- 323
- 3
- 11