Skip to content Skip to sidebar Skip to footer

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(newJsInterface(), "AndroidApp");
WebView.loadUrl("javascript:doStringToMyAndroid('This string from android')")

JsInterface:

publicclassJsInterface() {
    @JavascriptInterfacevoidreceiveString(String value) {
        // String received from WebViewLog.d("MyApp", value);
    }
}

Javascript:

functiondoStringToMyAndroid(stringFromAndroid){
   var myJsString = "Hello World" + ;
   // Call the JavascriptInterface instead of returning the valuewindow.AndroidApp.receiveString(myJsString);
}

But on API Level 19+, we now have the evaluateJavascript method:

WebView.evaluateJavascript("(function() { return getStringToMyAndroid('" + myJsString + "'); })();", newValueCallback<String>() {
    @OverridepublicvoidonReceiveValue(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"