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

后端 未结 1 985
既然无缘
既然无缘 2020-12-17 01:09

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

Sample,

function getStringToMyAndroid(stringFromAndroid){
   var myJsString = \"Hello          


        
相关标签:
1条回答
  • 2020-12-17 01:38

    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
        }
    });
    
    0 讨论(0)
提交回复
热议问题