WebViewJSBridge源码很简单,只有一个类,下面是这个类的类图(去除了OSX平台的代码)。
JS和Native的交互主要通过发送WVJBMessage消息来完成,它是一个字典,有五个字段:
- data,交互数据
- callbackId,是一个字符串,结构为objc_cb_(_uniqueid),_uniqueId是一个全局自增的整型变量
- handlerName,回调名称
- responseId,js调用native时使用,对应callbackId,标示是否是针对请求的回复
- responseData,js调用native时使用
JS调用Native
JS调用Native的技巧是:定义了一个专用scheme和host,在webView的- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
代理中判断是否是这个scheme来判断请求是否来自jsBridge,通过host判断是否有新消息,如果有,则主动调用协议定义的js方法来获取消息。
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (webView != _webView) { return YES; }
NSURL *url = [request URL];
__strong WVJB_WEBVIEW_DELEGATE_TYPE* strongDelegate = _webViewDelegate;
if ([[url scheme] isEqualToString:kCustomProtocolScheme]) {
if ([[url host] isEqualToString:kQueueHasMessage]) {
[self _flushMessageQueue];//确认js想调用native
} else {
NSLog(@"WebViewJavascriptBridge: WARNING: Received unknown WebViewJavascriptBridge command %@://%@", kCustomProtocolScheme, [url path]);
}
return NO;//来自jsbridge的请求不会加载
} else if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
return [strongDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
} else {
return YES;
}
}
_flushMessage主要分为下面几个步骤:
1.主动调用WebViewJavascriptBridge._fetchQueue()获取消息队列;
2.循环遍历消息队列
3.解析message,针对不同情况进行不同的处理
- (void)_flushMessageQueue {
//调用jsBridge协议的方法来获取js端想发送的信息
NSString *messageQueueString = [_webView stringByEvaluatingJavaScriptFromString:@"WebViewJavascriptBridge._fetchQueue();"];
id messages = [self _deserializeMessageJSON:messageQueueString];
if (![messages isKindOfClass:[NSArray class]]) {
NSLog(@"WebViewJavascriptBridge: WARNING: Invalid %@ received: %@", [messages class], messages);
return;
}
for (WVJBMessage* message in messages) {
if (![message isKindOfClass:[WVJBMessage class]]) {
NSLog(@"WebViewJavascriptBridge: WARNING: Invalid %@ received: %@", [message class], message);
continue;
}
[self _log:@"RCVD" json:message];
//取出responseId
NSString* responseId = message[@"responseId"];
if (responseId) {
/*
*这个分支说明这个消息是针对native调用js的响应
*取出这个responseId的回调,并且执行完毕后从字典中移除
*/
WVJBResponseCallback responseCallback = _responseCallbacks[responseId];
responseCallback(message[@"responseData"]);
[_responseCallbacks removeObjectForKey:responseId];
} else {
//这个分支说明是js主动想调用native
WVJBResponseCallback responseCallback = NULL;
NSString* callbackId = message[@"callbackId"];
if (callbackId) {
responseCallback = ^(id responseData) {
if (responseData == nil) {
responseData = [NSNull null];
}
WVJBMessage* msg = @{ @"responseId":callbackId, @"responseData":responseData };
[self _queueMessage:msg];//执行完毕后,发送消息给js,通知调用已经完毕
};
} else {
responseCallback = ^(id ignoreResponseData) {
// Do nothing
};
}//设置调用native后的处理回调
WVJBHandler handler;
if (message[@"handlerName"]) {
handler = _messageHandlers[message[@"handlerName"]];
} else {
handler = _messageHandler;
}
if (!handler) {
[NSException raise:@"WVJBNoHandlerException" format:@"No handler for message from JS: %@", message];
}
//执行调用
handler(message[@"data"], responseCallback);
}
}
}
Native调用JS
这个过程是比较简单的,直接调用stringByEvaluatingJavaScriptFromString即可。主要分为两步步:
- 调用提供的send接口
- 构建一个message,如果队列存在塞入队列,如果不存在直接dispatch
下面是主要的源码:
-(void)_sendData:(id)data responseCallback:(WVJBResponseCallback)responseCallback handlerName:(NSString*)handlerName {
NSMutableDictionary* message = [NSMutableDictionary dictionary];
if (data) {
message[@"data"] = data;
}
if (responseCallback) {
//将回调注册到_responseCallbacks中
NSString* callbackId = [NSString stringWithFormat:@"objc_cb_%ld", ++_uniqueId];
_responseCallbacks[callbackId] = [responseCallback copy];
message[@"callbackId"] = callbackId;
}
if (handlerName) {
message[@"handlerName"] = handlerName;
}
[self _queueMessage:message];
}
- (void)_queueMessage:(WVJBMessage*)message {
//如果queue存在,则加入到queue中,否则直接调用dispatchMessage
if (_startupMessageQueue) {
[_startupMessageQueue addObject:message];
} else {
[self _dispatchMessage:message];
}
}
//将Message字典序列化成JSON,主线程调用JS方法。
- (void)_dispatchMessage:(WVJBMessage*)message {
NSString *messageJSON = [self _serializeMessage:message];
[self _log:@"SEND" json:messageJSON];
NSLog(@"%@ %@", message ,messageJSON);
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\f" withString:@"\\f"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\u2028" withString:@"\\u2028"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\u2029" withString:@"\\u2029"];
NSLog(@"%@ %@", message ,messageJSON);
NSString* javascriptCommand = [NSString stringWithFormat:@"WebViewJavascriptBridge._handleMessageFromObjC('%@');", messageJSON];
if ([[NSThread currentThread] isMainThread]) {
[_webView stringByEvaluatingJavaScriptFromString:javascriptCommand];
} else {
__strong WVJB_WEBVIEW_TYPE* strongWebView = _webView;
dispatch_sync(dispatch_get_main_queue(), ^{
[strongWebView stringByEvaluatingJavaScriptFromString:javascriptCommand];
});
}
}