Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

android - 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;
}

Now I want calling function getStringToMyAndroid("This string from android") and get the returning 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 the JS function but I want to get the string or value from JS function

NOTE: My android running on minimum SDK Android 3.0 honeycomb

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...