I want to override the behavior of back button in a WebView
in Android so when an exact menu is open in the webpage (in the WebView
), the back button should close the menu instead of going to previous page.
I know how to be able to send data from JavaScript to Android, but I am confused about how to use the callback data in if()
blocks (which is not presented in the accepted answer of linked question):
Ok. The logic I used is something like these codes:
if ( isMenuOpen() ){
closeMenu();
return true;
}
else{
//Let the back button do its default behavior
}
isMenuOpen()
calls a JavaScript function to check if menu is open:
public void isMenuOpen(){
webview.loadUrl="javascript:isMenuOpen()";
}
And this is my JavaScript function which passes the result into a Java function using JavaScriptInterface
:
function isMenuOpen(){
if ($(".menu").hasClass("open")){
jInterface.resultFunction(true);
}
else{
jInterface.resultFunction(false);
}
}
And this is the final Java function which retrieves the data from JavaScript output:
@JavascriptInterface
public boolean resultFunction(boolean result){
return result;
}
The problem is that isMenuOpen()
is a void function which only calls a JavaScript function. How should I change the logic to get the final result in isMenuOpen()
?