什么是JsBridge?
App开发中通过native+H5的方式实现一些开发,这就需要一个中间组件来实现Native和H5之间的交互,这就是JsBridge。本文对 开源JsBridge 项目的源码进行分析。
JsBridge交互分为native调用H5和H5调用native两部分,该项目的类图如下所示:
BridgeWebView
BridgeWebView继承自WebView,并实现了WebViewJavascriptBridge接口,用于加载H5。要实现native和H5之间的互通,首先需要在native和H5之间建立一种协议,双方在通信时都得遵循这个协议,这个协议就是"WebViewJavascriptBridge.js。BridgeWebView加载H5时首先需要加载这个js脚本:
private void init() {
this.setVerticalScrollBarEnabled(false);
this.setHorizontalScrollBarEnabled(false);
this.getSettings().setJavaScriptEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
this.setWebViewClient(generateBridgeWebViewClient());
}
protected BridgeWebViewClient generateBridgeWebViewClient() {
return new BridgeWebViewClient(this);
}
协议的加载就在BridgeWebViewClient.onPageFinish中
public static final String toLoadJs = "WebViewJavascriptBridge.js";
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (BridgeWebView.toLoadJs != null) {
BridgeUtil.webViewLoadLocalJs(view, BridgeWebView.toLoadJs);
}
}
BridgeUtil.webViewLoadLocalJs:
//在H5界面加载完成后加载WebViewJavascriptBridge.js文件
public static void webViewLoadLocalJs(WebView view, String path){
String jsContent = assetFile2Str(view.getContext(), path);
view.loadUrl("javascript:" + jsContent);
}
public static String assetFile2Str(Context c, String urlStr){
InputStream in = null;
try{
in = c.getAssets().open(urlStr);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
if (line != null && !line.matches("^\\s*\\/\\/.*")) { // 去除注释
sb.append(line);
}
} while (line != null);
bufferedReader.close();
in.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
return null;
}
WebViewJavascriptBridge.js到底长啥样?
(function() {
if (window.WebViewJavascriptBridge) {
return;
}
//通过设置messagingIframe.src触发WebView的shouldOverrideUrlLoading,
//告知native H5有消息,注意这里并没有携带消息体
//url为yy://__QUEUE_MESSAGE__/
var messagingIframe;
//bizMessagingIframe.src触发WebView的shouldOverrideUrlLoading,
//告知native H5有消息,注意这里会携带消息体
//url为yy://://return/_fetchQueue/消息体json字符串
var bizMessagingIframe;
var sendMessageQueue = [];//H5发送给native的消息队列
var receiveMessageQueue = [];/H5接受到native的消息队列
var messageHandlers = {};//H5注册给Js的处理器,用于处理native发来的消息
var CUSTOM_PROTOCOL_SCHEME = 'yy';
var QUEUE_HAS_MESSAGE = '__QUEUE_MESSAGE__/';
//H5将消息发送给native,如果H5需要接受native的反馈,就需要提供一个callback
//responseCallbacks中保存着H5提供的回调,以key-value的形式保存,key对应callbackId,value对应着回调
var responseCallbacks = {};
var uniqueId = 1;
// 创建消息index队列iframe
function _createQueueReadyIframe(doc) {
messagingIframe = doc.createElement('iframe');
messagingIframe.style.display = 'none';
doc.documentElement.appendChild(messagingIframe);
}
//创建消息体队列iframe
function _createQueueReadyIframe4biz(doc) {
bizMessagingIframe = doc.createElement('iframe');
bizMessagingIframe.style.display = 'none';
doc.documentElement.appendChild(bizMessagingIframe);
}
//set default messageHandler 初始化默认的消息线程
function init(messageHandler) {
if (WebViewJavascriptBridge._messageHandler) {
throw new Error('WebViewJavascriptBridge.init called twice');
}
WebViewJavascriptBridge._messageHandler = messageHandler;
var receivedMessages = receiveMessageQueue;
receiveMessageQueue = null;
//初始化时查看是否已经有native消息过来了,有的话需要处理
for (var i = 0; i < receivedMessages.length; i++) {
_dispatchMessageFromNative(receivedMessages[i]);
}
}
//H5发送data给native,提供给H5使用
function send(data, responseCallback) {
_doSend({
data: data
}, responseCallback);
}
//H5注册处理器,native发送消息来的时候取handlerName对应的handler进行处理
function registerHandler(handlerName, handler) {
messageHandlers[handlerName] = handler;
}
//ja提供给H5调用,指定了handlerName
function callHandler(handlerName, data, responseCallback) {
_doSend({
handlerName: handlerName,
data: data
}, responseCallback);
}
//H5发送消息给native native处理
function _doSend(message, responseCallback) {
if (responseCallback) {
var callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime();
responseCallbacks[callbackId] = responseCallback;
message.callbackId = callbackId;
}
sendMessageQueue.push(message);
//触发shouldOverrideUrlLoading="yy://__QUEUE_MESSAGE__/"
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
}
// 提供给native调用,该函数作用:获取sendMessageQueue返回给native
// shouldOverrideUrlLoading在检测到"yy://__QUEUE_MESSAGE__/"调用javascript:WebViewJavascriptBridge._fetchQueue();
function _fetchQueue() {
var messageQueueString = JSON.stringify(sendMessageQueue);
sendMessageQueue = [];
//触发shouldOverrideUrlLoading="yy://://return/_fetchQueue/消息体json字符串"
bizMessagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://return/_fetchQueue/' + encodeURIComponent(messageQueueString);
}
//提供给native使用,native通过"javascript:WebViewJavascriptBridge._handleMessageFromNative('%s');"调用到
function _dispatchMessageFromNative(messageJSON) {
setTimeout(function() {
//解析native传来的数据
var message = JSON.parse(messageJSON);
var responseCallback;
//native调用js,如果传来的消息有responseId,说明这个消息是js调用native后native返回的
//需要回调js的callback
if (message.responseId) {
responseCallback = responseCallbacks[message.responseId];
if (!responseCallback) {
return;
}
responseCallback(message.responseData);
delete responseCallbacks[message.responseId];
} else {//native直接调用js的消息
//callbackId不为空,说明需要回调native
if (message.callbackId) {
var callbackResponseId = message.callbackId;
//通过_doSend将消息返回给native
responseCallback = function(responseData) {
_doSend({
responseId: callbackResponseId,
responseData: responseData
});
};
}
var handler = WebViewJavascriptBridge._messageHandler;
//查询H5注册给js的handler
if (message.handlerName) {
handler = messageHandlers[message.handlerName];
}
try {
//H5注册给js的handler,并回调responseCallback
handler(message.data, responseCallback);
} catch (exception) {
if (typeof console != 'undefined') {
console.log("WebViewJavascriptBridge: WARNING: javascript handler threw.", message, exception);
}
}
}
});
}
//提供给native调用,receiveMessageQueue 在会在页面加载完后赋值为null,所以
function _handleMessageFromNative(messageJSON) {
console.log(messageJSON);
if (receiveMessageQueue) {
receiveMessageQueue.push(messageJSON);
}
_dispatchMessageFromNative(messageJSON);
}
var WebViewJavascriptBridge = window.WebViewJavascriptBridge = {
init: init,
send: send,
registerHandler: registerHandler,
callHandler: callHandler,
_fetchQueue: _fetchQueue,
_handleMessageFromNative: _handleMessageFromNative
};
var doc = document;
_createQueueReadyIframe(doc);
_createQueueReadyIframe4biz(doc);
var readyEvent = doc.createEvent('Events');
readyEvent.initEvent('WebViewJavascriptBridgeReady');
readyEvent.bridge = WebViewJavascriptBridge;
doc.dispatchEvent(readyEvent);
})();
通过WebViewJavascriptBridge.js是一个匿名自运行的js function,加载之后就能运行,从而实现native和H5之间的交互。
BridgeWebView.registerHandler
Map<String, BridgeHandler> messageHandlers = new HashMap<String, BridgeHandler>();
/**
* 注册处理程序,以便javascript调用它
*handlerName对应js调用时传的名字
*/
public void registerHandler(String handlerName, BridgeHandler handler) {
if (handler != null) {
// 添加至 Map<String, BridgeHandler>
messageHandlers.put(handlerName, handler);
}
}
BridgeWebView提供registerHandler API给native使用,
例如通过如下方式注册handler:
webView.registerHandler("submitFromWeb", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Log.i(TAG, "handler = submitFromWeb, data from web = " + data);
function.onCallBack("submitFromWeb exe, response data 中文 from Java");
}
});
注册完成后,native就能处理H5发来的handlerName为"submitFromWeb"的消息。同样,function.onCallBack可以将native处理后的数据发回给H5。
WebViewJavascriptBridge.registerHandler
//H5注册处理器,native发送消息来的时候取handlerName对应的handler进行处理
function registerHandler(handlerName, handler) {
messageHandlers[handlerName] = handler;
}
WebViewJavascriptBridge提供该API给H5使用:
bridge.registerHandler("functionInJs", function(data, responseCallback) {
document.getElementById("show").innerHTML = ("data from Java: = " + data);
if (responseCallback) {
var responseData = "Javascript Says Right back aka!";
responseCallback(responseData);
}
});
通过这种方式,H5就能注册handlerName为"functionInJs"的处理器,这样native在发送消息时,如果handlerName为"functionInJs",就会触发对应的处理器,处理完成后同样可以将结果发回个native
BridgeWebViewClient
BridgeWebViewClient最主要如下:
//H5通过这种方式调用native
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) {
// 如果是返回数据yy://return/{function}/returncontent
webView.handlerReturnData(url);
return true;
} else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) {
//不是返回数据yy://,就去刷新消息队列,触发
//调用js的_fetchQueue,这个会触发YY_RETURN_DATA
webView.flushMessageQueue();
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
H5通过设置url的形式触发shouldOverrideUrlLoading方法,通过这种方式完成H5调用native
H5调用native的过程如下
1、native首先调用BridgeWebView.registerHandler注册native的处理器:
webView.registerHandler("submitFromWeb", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Log.i(TAG, "handler = submitFromWeb, data from web = " + data);
function.onCallBack("submitFromWeb exe, response data 中文 from Java");
}
});
2、H5调用WebViewJavascriptBridge.send函数
function testClick() {
var str1 = document.getElementById("text1").value;
var str2 = document.getElementById("text2").value;
//send message to native
var data = {id: 1, content: "这是一个图片 <img src=\"a.png\"/> test\r\nhahaha"};
window.WebViewJavascriptBridge.send(
data , function(responseData) {
document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData
}
);
}
在加载H5的时候已经加载了WebViewJavascriptBridge.js,所以可以直接调用,WebViewJavascriptBridge.send()如下所示:
//H5发送data给native,提供给H5使用
function send(data, responseCallback) {
_doSend({
data: data
}, responseCallback);
}
3、调用WebViewJavascriptBridge._doSend函数
//H5发送消息给native native处理
function _doSend(message, responseCallback) {
if (responseCallback) {
var callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime();
responseCallbacks[callbackId] = responseCallback;
message.callbackId = callbackId;
}
sendMessageQueue.push(message);
//触发shouldOverrideUrlLoading="yy://__QUEUE_MESSAGE__/"
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
}
H5在调用native时如果需要获取到结果,则需要给_doSend设置responseCallback,设置后,就会给将该callback保存到responseCallbacks[]数组中,在调用native结束后,native会通过js的方式将结果回调给H5,这时就需要从responseCallbacks取出对应的回调函数。
_doSend将Message存放到sendMessageQueue中,并设置messagingIframe.src以调用WebView的shouldOverrideUrlLoading:
yy://__QUEUE_MESSAGE__
4、WebView的shouldOverrideUrlLoading检查链接类型
webView.flushMessageQueue();
触发 webView.flushMessageQueue:
void flushMessageQueue() {
//必须正在主线程
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
//调用js的"javascript:WebViewJavascriptBridge._fetchQueue();"
loadUrl(BridgeUtil.JS_FETCH_QUEUE_FROM_JAVA, new CallBackFunction() {
@Override
public void onCallBack(String data) {//H5回调给native
//......
}
});
}
}
public void loadUrl(String jsUrl, CallBackFunction returnCallback) {
this.loadUrl(jsUrl);//native调用js的方法
//如果调用H5时需要响应H5的结果回调,则需要将returnCallback保存下来
responseCallbacks.put(BridgeUtil.parseFunctionName(jsUrl), returnCallback);
}
flushMessageQueue通过loadUrl调用javascript:WebViewJavascriptBridge._fetchQueue()获取H5的所有数据。
5、WebViewJavascriptBridge._fetchQueue()
// 提供给native调用,该函数作用:获取sendMessageQueue返回给native
// shouldOverrideUrlLoading在检测到"yy://__QUEUE_MESSAGE__/"调用javascript:WebViewJavascriptBridge._fetchQueue();
function _fetchQueue() {
var messageQueueString = JSON.stringify(sendMessageQueue);
sendMessageQueue = [];
//触发shouldOverrideUrlLoading="yy://://return/_fetchQueue/消息体json字符串"
bizMessagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://return/_fetchQueue/' + encodeURIComponent(messageQueueString);
}
_fetchQueue将sendMessageQueue中的数据通过"yy://://return/_fetchQueue/消息体json字符串"的形式传给shouldOverrideUrlLoading,BridgeWebView在检测到该url后调用:
如果是返回数据yy://return/{function}/returncontent
webView.handlerReturnData(url);
6、BridgeWebView.handlerReturnData
void handlerReturnData(String url) {
String functionName = BridgeUtil.getFunctionFromReturnUrl(url);
CallBackFunction f = responseCallbacks.get(functionName);
String data = BridgeUtil.getDataFromReturnUrl(url);
if (f != null) {
f.onCallBack(data);
responseCallbacks.remove(functionName);
return;
}
}
在获取到H5发来的信息后,就查询native对应的CallBackFunction进行处理,第4步loadUrl的时候讲CallBackFunction和functionName的对应关系保存到了responseCallbacks,这样这里就可以取出来进行回调,第4步注册的回调如下:
new CallBackFunction() {
@Override
public void onCallBack(String data) {//H5回调给native
// deserializeMessage 反序列化消息
List<Message> list = null;
try {
list = Message.toArrayList(data);
} catch (Exception e) {
e.printStackTrace();
return;
}
if (list == null || list.size() == 0) {
return;
}
for (int i = 0; i < list.size(); i++) {
Message m = list.get(i);
String responseId = m.getResponseId();
//H5发给native的消息含有responseId,说明这个消息是native调用H5后H5返回的,则需要回调给native的调用方
if (!TextUtils.isEmpty(responseId)) {
//找到native对应的CallBackFunction
CallBackFunction function = responseCallbacks.get(responseId);
String responseData = m.getResponseData();
function.onCallBack(responseData);
responseCallbacks.remove(responseId);
} else {//H5调用native,不是响应
CallBackFunction responseFunction = null;
//本次如果有回调Id,说明native在调用结束后需要将结果告知H5
final String callbackId = m.getCallbackId();
if (!TextUtils.isEmpty(callbackId)) {
responseFunction = new CallBackFunction() {
@Override
public void onCallBack(String data) {
//将native处理完后的数据回调给H5
Message responseMsg = new Message();
responseMsg.setResponseId(callbackId);
responseMsg.setResponseData(data);
queueMessage(responseMsg);
}
};
} else {
responseFunction = new CallBackFunction() {
@Override
public void onCallBack(String data) {
// do nothing
}
};
}
//查找handlerName对应BridgeHandler来执行H5的请求,webView.registerHandler注册了处理器
BridgeHandler handler;
if (!TextUtils.isEmpty(m.getHandlerName())) {
handler = messageHandlers.get(m.getHandlerName());
} else {
handler = defaultHandler;
}
if (handler != null){
handler.handler(m.getData(), responseFunction);
}
}
}
}
});
在调用handler的处理函数时,如果插入了responseFunction,说明在native处理完后需要将处理结果传个H5。这时调用:
//将native处理完后的数据回调给H5
Message responseMsg = new Message();
responseMsg.setResponseId(callbackId);
responseMsg.setResponseData(data);
queueMessage(responseMsg);
这里个responseMsg设置了responseId,告知H5这是个响应消息,H5不需要再回应native了。
queueMessage->dispatchMessage
void dispatchMessage(Message m) {
String messageJson = m.toJson();
//escape special characters for json string 为json字符串转义特殊字符
messageJson = messageJson.replaceAll("(\\\\)([^utrn])", "\\\\\\\\$1$2");
messageJson = messageJson.replaceAll("(?<=[^\\\\])(\")", "\\\\\"");
messageJson = messageJson.replaceAll("(?<=[^\\\\])(\')", "\\\\\'");
String javascriptCommand = String.format(BridgeUtil.JS_HANDLE_MESSAGE_FROM_JAVA, messageJson);
// 必须要找主线程才会将数据传递出去 --- 划重点
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
Log.i("zpy","dispatchMessage:"+javascriptCommand);
this.loadUrl(javascriptCommand);
}
dispatchMessage通过WebView.loadUrl将响应数据交给H5。
至此,一次H5调用native的过程就结束了。
native调用H5
1、BridgeWebView提供callHandler和send两个函数给native调用H5,两种方式最终都调用了doSend函数:
private void doSend(String handlerName, String data, CallBackFunction responseCallback) {
Message m = new Message();
if (!TextUtils.isEmpty(data)) {
m.setData(data);
}
if (responseCallback != null) {
String callbackStr = String.format(BridgeUtil.CALLBACK_ID_FORMAT, ++uniqueId + (BridgeUtil.UNDERLINE_STR + SystemClock.currentThreadTimeMillis()));
responseCallbacks.put(callbackStr, responseCallback);
m.setCallbackId(callbackStr);
}
if (!TextUtils.isEmpty(handlerName)) {
m.setHandlerName(handlerName);
}
queueMessage(m);
}
这里在调用H5之前,保存了callbackStr和responseCallback的对应关系,说明调用H5,native需要接受H5的返回结果。接着调用了dispatchMessage,调用了
"javascript:WebViewJavascriptBridge._handleMessageFromNative('%s');"
2、WebViewJavascriptBridge._dispatchMessageFromNative
//提供给native使用,native通过"javascript:WebViewJavascriptBridge._handleMessageFromNative('%s');"调用到
function _dispatchMessageFromNative(messageJSON) {
setTimeout(function() {
//解析native传来的数据
var message = JSON.parse(messageJSON);
var responseCallback;
//native调用js,如果传来的消息有responseId,说明这个消息是js调用native后native返回的
//需要回调js的callback
if (message.responseId) {
responseCallback = responseCallbacks[message.responseId];
if (!responseCallback) {
return;
}
responseCallback(message.responseData);
delete responseCallbacks[message.responseId];
} else {//native直接调用js的消息
//callbackId不为空,说明需要回调native
if (message.callbackId) {
var callbackResponseId = message.callbackId;
//通过_doSend将消息返回给native
responseCallback = function(responseData) {
_doSend({
responseId: callbackResponseId,
responseData: responseData
});
};
}
var handler = WebViewJavascriptBridge._messageHandler;
//查询H5注册给js的handler
if (message.handlerName) {
handler = messageHandlers[message.handlerName];
}
try {
//交易H5注册个js的handler,并回调responseCallback
handler(message.data, responseCallback);
} catch (exception) {
if (typeof console != 'undefined') {
console.log("WebViewJavascriptBridge: WARNING: javascript handler threw.", message, exception);
}
}
}
});
}
该函数提供给native调用,会分发native的请求,如果message.ResponseId不为空,说明该消息是H5调用native后返回的数据,直接将结果返回给对应的js function即可。
如果ResponseId为空,说明这是native的一个全新的请求,这时候就需要查看message.callbackId,callBackId不为空,说明在H5处理完请求后,需要将结果返回给native。H5处理native的请求也是通过handler实现的。那么这个handler哪里来的呢??
//H5注册处理器,native发送消息来的时候取handlerName对应的handler进行处理
function registerHandler(handlerName, handler) {
messageHandlers[handlerName] = handler;
}
答案就在这边,WebViewJavascriptBridge.js提供了registerHandler给H5注册处理器,下面代码就是注册了"functionInJs"对应的处理器。
bridge.registerHandler("functionInJs", function(data, responseCallback) {
document.getElementById("show").innerHTML = ("data from Java: = " + data);
if (responseCallback) {
var responseData = "Javascript Says Right back aka!";
responseCallback(responseData);
}
});
注册处理器中,如果有responseCallback,则需要将H5处理的结果返回,responseCallback的实现如下,他将结果通过_doSend发给了native
//通过_doSend将消息返回给native
responseCallback = function(responseData) {
_doSend({
responseId: callbackResponseId,
responseData: responseData
});
};