How can I call javascript function and get return value from javascript function

I want to get the value from my JS function on my Java-Android

Example

function getStringToMyAndroid(stringFromAndroid){ var myJsString = "Hello World" + ; return myJsString; } 

Now I want to call the getStringToMyAndroid function ("This line is from android") and get the returned myJsString on my Android, so I can use myJsString later on my Android;

I know I can use

 WebView.loadUrl("javascript:getStringToMyAndroid('This string from android')") 

to call a JS function, but I want to get a string or value from a JS function

NOTE. My android runs on the minimum Android 3.0 cellular SDK

+6
source share
1 answer

For API level <19, there are only workarounds for using JavascriptInterface (my preferred method below) or grabbing the OnJsAlert method and using the alert() dialog. This means that you cannot 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 at API level 19+, we now have a methodJavascript 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 } }); 
+13
source

Source: https://habr.com/ru/post/973208/


All Articles