简体   繁体   English

我如何调用javascript函数并从javascript函数获取返回值

[英]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 我想从我的Java Android上的JS函数中获取值

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; 现在我想要调用函数getStringToMyAndroid(“来自android的这个字符串”)并在我的Android上获取返回的myJsString ,所以我可以稍后在我的Android上使用myJsString ;

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 调用JS函数,但我想从JS函数中获取字符串或值

NOTE: My android running on minimum SDK Android 3.0 honeycomb 注意:我的Android运行在最小的SDK Android 3.0蜂窝上

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. 对于API级别<19,只有使用JavascriptInterface(我的首选方法,下面)或者劫持OnJsAlert方法并使用alert()对话框的解决方法。 That then means you can't use the alert() function for its intended purpose. 这意味着您不能将alert()函数用于其预期目的。

View: 视图:

WebView.addJavascriptInterface(new JsInterface(), "AndroidApp");
WebView.loadUrl("javascript:doStringToMyAndroid('This string from android')")

JsInterface: JsInterface:

public class JsInterface() {
    @JavascriptInterface
    void receiveString(String value) {
        // String received from WebView
        Log.d("MyApp", value);
    }
}

Javascript: 使用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: 但是在API Level 19+上,我们现在有了evaluateJavascript方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM