How I Can Call Javascript Function And Get The Return Value From Javascript Function
I want to get the value from my JS function on my Java Android Sample, function getStringToMyAndroid(stringFromAndroid){ var myJsString = 'Hello World' + ; return myJsString;
Solution 1:
For API Level < 19 there are only workarounds of either using a JavascriptInterface (my preferred method, below) or else hijacking the OnJsAlert method and using the alert()
dialog instead. That then means you can't use the alert()
function for its intended purpose.
View:
WebView.addJavascriptInterface(new JsInterface(), "AndroidApp");
WebView.loadUrl("javascript:doStringToMyAndroid('This string from android')")
JsInterface:
public class JsInterface() {
@JavascriptInterface
void receiveString(String value) {
// String received from WebView
Log.d("MyApp", value);
}
}
Javascript:
function doStringToMyAndroid(stringFromAndroid){
var myJsString = "Hello World" + ;
// Call the JavascriptInterface instead of returning the value
window.AndroidApp.receiveString(myJsString);
}
But on API Level 19+, we now have the evaluateJavascript method:
WebView.evaluateJavascript("(function() { return getStringToMyAndroid('" + myJsString + "'); })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
Log.d("LogName", s); // Returns the value from the function
}
});
Post a Comment for "How I Can Call Javascript Function And Get The Return Value From Javascript Function"