是的,Android 在这方面确实很出色。
我正在发布来自我制作的随机示例应用程序的示例代码,但这应该可以帮助您继续。
让我们首先假设您必须将全局变量添加到您的 webview 控制类中:
String name = "John";
String lastName = "Doe";
在控制 webview 的 Android 类中(期间onCreate()
或者当你设置你的网络视图时):
webView.addJavascriptInterface(new JavaScriptInterface(), "android")
webview 控制类的内部类:
/**
* Sets up the interface for getting access to Latitude and Longitude data
* from device
**/
private class JavaScriptInterface {
public String getName() {
return name;
}
public String getLastName() {
return lastName;
}
public void onJavascriptButtonPushed(String text) {
Toast.makeText(WebViewControllingClass.this, "The text of the pressed button is: "+text,Toast.LENGTH_SHORT).show();
}
}
Android 端就是这样,现在通过 Javascript 使用它:
要通过 JavaScript 获取姓名:
if (window.android){
name = window.android.getName();
lastName = window.android.getLastName();
}
如果你想举杯,请设置一个javascript,其功能为:
if (window.android){
window.android.onJavascriptButtonPushed("Hello");
}
Edit:
我没试过这个,但是search https://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview产生了这个,尝试一下,它应该有效。
如果你想在另一个方向使用它:
JS:
function testEcho(message){
window.JSInterface.doEchoTest(message);
}
Android:
myWebView.loadUrl("javascript:testEcho('Hello World!')");