javascript 我如何调用javascript函数并从javascript函数获取返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25074903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How I can call javascript function and get the return value from javascript function
提问by ilovebali
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 myJsStringon my Android, so I can use myJsStringlater on my Android;
现在我想调用函数getStringToMyAndroid("This string from 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 蜂窝上
回答by CodingIntrigue
For API Level < 19 there are only workarounds of either using a JavascriptInterface (my preferred method, below) or else hiHymaning the OnJsAlert method and using the alert()
dialog instead. That then means you can't use the alert()
function for its intended purpose.
对于 API 级别 < 19,只有使用 JavascriptInterface(我的首选方法,如下)或劫持 OnJsAlert 方法并改用alert()
对话框的解决方法。这意味着您不能将该alert()
功能用于其预期目的。
View:
看法:
WebView.addJavascriptInterface(new JsInterface(), "AndroidApp");
WebView.loadUrl("javascript:doStringToMyAndroid('This string from android')")
JsInterface:
Js接口:
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 级别 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
}
});