Android 与 Android-WebView 控件中的 JavaScript 交互

Android 层加载 html, 获取到网页对象

1
2
3
//////////////////// Android 层 ////////////////////////
var webView = (BridgeWebView) findViewById(R.id.webView);
webView.loadUrl("file:///android_asset/demo.html");

Android 层操作(注册 Android 监听事件与触发 Js 事件)

注册 android 默认事件

webView.setDefaultHandler(new DefaultHandler());

注册 android 监听事件

1
2
3
4
5
6
7
webView.registerHandler("functionInJava", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction cb) {
Log.i(TAG, "handler = functionInJava, data from web = " + data);
cb.onCallBack("functionInJava exe, response data from Java");
}
});

触发 js 默认事件

webView.send("hello");

触发 js 监听事件

1
2
3
4
5
6
webView.callHandler("functionInJs", "send data to js", new CallBackFunction() {
@Override
public void onCallBack(String data) {

}
});

JS 层操作(注册 Js 监听事件与触发 Android 事件)

触发 android 默认事件

1
2
3
4
5
6
7
var data = {id: 1, content: "this is html test <img src=\"a.png\"/> test\r\nhahaha"};
window.WebViewJavascriptBridge.send(
data
, function(responseData) {
document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData
}
);

触发 android 监听事件

1
2
3
4
5
6
7
window.WebViewJavascriptBridge.callHandler(
'functionInJava'
, {'param': str1}
, function(responseData) {
document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData
}
);

注册 js 监听事件 - 通用接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function() {
callback(WebViewJavascriptBridge)
},
false
);
}
}

connectWebViewJavascriptBridge(function(bridge) {
// 注册js默认事件
bridge.init(function(message, responseCallback) {
console.log('JS got a message', message);
var data = {
'Javascript Responds': 'Wee!'
};
console.log('JS responding with', data);
responseCallback(data);
});

// 注册js监听事件
bridge.registerHandler("functionInJs", function(data, responseCallback) {
document.getElementById("show").innerHTML = ("data from Java: = " + data);
var responseData = "Javascript Says Right back aka!";
responseCallback(responseData);
});
});
Donate - Support to make this site better.
捐助 - 支持我让我做得更好.