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
}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…