注:本文需同时了解iOS和h5相关开发技能开发者查看,此处以h5调iOS客户端为例
iOS调h5,流程比较简单,此处不做分析
简介:
当前移动互联背景下,移动应用市场越来越小,基本都是各大厂和政府的利民软件才能存活,为了提高效率,节约成本,小一点的公司,直接跨平台开发,什么Flutter,React用起来,UI干着产品的活,公司全员都是测试,开发没有技能限制,都得会,所以移动开发人员的生存空间也越来越小,市场也已经卷的不成样子。大点的公司在用户体验上要求稍微高点,会给原生留出一丝生存空间,但在大环境下,嵌入H5是必不可少的。而大量交互,用原生方法或多或少会有些问题,而且开发起来也比较复杂,因此大多采用JSBridage。对于JSBridge,可能有些人会陌生,大多数人也只是会用,其实会用就够了。那么为什么还要去了解其原理呢,还不都是为了不被卷。
另:本文如有不当之处,还请指出
1,iOS客户端注册js方法
注册js方法时,会以方法名为key,并同时生成一个block作为回调函数,作为value,存储在一个全局的字典中。
1,iOS 注册js方法
[_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testObjcCallback called: %@", data);
responseCallback(@"Response from testObjcCallback");
}];
2,全局字典保存相关数据
- (void)registerHandler:(NSString *)handlerName handler:(WVJBHandler)handler {
_base.messageHandlers[handlerName] = [handler copy];
}
2,客户端加载网页,h5开始加载jsbridge.js文件
在jsbridge.js文件中,iframe控件会被注入,其内src里https://bridge_loaded 地址会被执行加载
jsbridge.js文件
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge)
{
return callback(WebViewJavascriptBridge);
}
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback);
}
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'https://__bridge_loaded__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
setupWebViewJavascriptBridge(function(bridge) {
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
responseCallback("回调客户端数据");
})
bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
//response为客户端传入数据
})
})
3,iOS端第一次拦截地址
1,在jsbridge库中,WKWebviewBridge文件(UIWebView已被舍弃,不做考虑),在webview将要加载一个链接的代理中,会对加载地址判断,当收到https://bridge_loaded/ 连接后,对其拦截。
injectJavascriptFile 方法生成js代码
- (void)injectJavascriptFile {
NSString *js = WebViewJavascriptBridge_js();
[self _evaluateJavascript:js];
if (self.startupMessageQueue) {
NSArray* queue = self.startupMessageQueue;
self.startupMessageQueue = nil;
for (id queuedMessage in queue) {
[self _dispatchMessage:queuedMessage];
}
}
}
2,库内会生成一段js代码,其内包含多个方法,registerHandler,callHandler,_fetchQueue,_handleMessageFromObjc等。
window.WebViewJavascriptBridge = {
registerHandler: registerHandler,
callHandler: callHandler,
disableJavscriptAlertBoxSafetyTimeout: disableJavscriptAlertBoxSafetyTimeout,
_fetchQueue: _fetchQueue,
_handleMessageFromObjC: _handleMessageFromObjC
};
3,此js代码向h5注入,赋值给Window的WebViewJavascriptBridge属性。
4,h5执行callHandler方法
bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
log('JS got response', response)
})
5,在callHandler方法里会调用_doSend()函数
function callHandler(handlerName, data, responseCallback) {
if (arguments.length == 2 && typeof data == 'function') {
responseCallback = data; data = null;
}
_doSend({
handlerName:handlerName, data:data
}, responseCallback);
}
6,js代码包含另一个iframe为message传递,src为https://_wvjb_queue_message/ 类型
_doSend函数会执行message 的iframe
function _doSend(message, responseCallback) {
if (responseCallback) {
var callbackId = 'cb_'+(uniqueId++)+'_'+new Date().getTime();
responseCallbacks[callbackId] = responseCallback;
message['callbackId'] = callbackId;
}
sendMessageQueue.push(message);
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
}
4,iOS客户端第二次拦截地址
1,当遇到https://_wvjb_queue_message/链接后链接
2,调用js代码注入中的WebViewJavascriptBridge.fetchQueue();方法
方法回调中包含h5调用callhandler的方法名,参数和callbackid。
3,h5执行WebViewJavascriptBridge.fetchQueue()函数
function _fetchQueue() {
var messageQueueString = JSON.stringify(sendMessageQueue);
sendMessageQueue = [];
return messageQueueString;
}
sendMessageQueue的内容,在_doSend()函数执行的后,把message,即h5要传的参数,push进去了。
4,iOS客户端根据方法名去除全局保存的函数,并调用把callbackid,data传递过去。
5,客户端在此时执行自己第一步注册的js方法的回调处理自有业务逻辑。
5,iOS回调h5
1,客户端处理之后,把相应结果,通过responseCallBacke继续回调
2,客户端调用注入的js代码中的WebViewJavascriptBridge._handleMessageFromObjC(data)方法
data的数据类型为
{
"responseId":"callbackid",
"responseData":"回调数据"
}
3,h5执行_handleMessageFromObjC函数,通过responseid,找到对应callhander函数的回调
6,h5处理回调数据
1,h5执行_handleMessageFromObjC方法,找到对应callHandler的方法,删除客户端回调数据中的responseId
function _handleMessageFromObjC(messageJSON) {
_dispatchMessageFromObjC(messageJSON);
}
function _dispatchMessageFromObjC(messageJSON) {
if (dispatchMessagesWithTimeoutSafety) {
setTimeout(_doDispatchMessageFromObjC);
} else {
_doDispatchMessageFromObjC();
}
function _doDispatchMessageFromObjC() {
var message = JSON.parse(messageJSON);
var messageHandler;
var responseCallback;
if (message.responseId) {
responseCallback = responseCallbacks[message.responseId];
if (!responseCallback) {
return;
}
responseCallback(message.responseData);
delete responseCallbacks[message.responseId];
} else {
if (message.callbackId) {
var callbackResponseId = message.callbackId;
responseCallback = function(responseData) {
_doSend({
handlerName:message.handlerName,
responseId:callbackResponseId,
responseData:responseData });
};
}
var handler = messageHandlers[message.handlerName];
if (!handler) {
console.log("WebViewJavascriptBridge: WARNING: no handler for message from ObjC:", message);
} else {
handler(message.data, responseCallback);
}
}
}
}
2,_handleMessageFromObjC方法回调,此时h5中的res后的函数执行,处理h5相关业务逻辑。
bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
//处理h5相关业务
})
此时,一次完整的交互流程结束
完整注入的js代码如下
; (function() {
if (window.WebViewJavascriptBridge) {
return;
}
if (!window.onerror) {
window.onerror = function(msg, url, line) {
console.log("WebViewJavascriptBridge: ERROR:" + msg + "@" + url + ":" + line);
}
}
window.WebViewJavascriptBridge = {
registerHandler: registerHandler,
callHandler: callHandler,
disableJavscriptAlertBoxSafetyTimeout: disableJavscriptAlertBoxSafetyTimeout,
_fetchQueue: _fetchQueue,
_handleMessageFromObjC: _handleMessageFromObjC
};
var messagingIframe;
var sendMessageQueue = [];
var messageHandlers = {};
var CUSTOM_PROTOCOL_SCHEME = 'https';
var QUEUE_HAS_MESSAGE = '__wvjb_queue_message__';
var responseCallbacks = {};
var uniqueId = 1;
var dispatchMessagesWithTimeoutSafety = true;
function registerHandler(handlerName, handler) {
messageHandlers[handlerName] = handler;
}
function callHandler(handlerName, data, responseCallback) {
if (arguments.length == 2 && typeof data == 'function') {
responseCallback = data; data = null;
} _doSend({
handlerName:handlerName, data:data
}, responseCallback);
}
function disableJavscriptAlertBoxSafetyTimeout() {
dispatchMessagesWithTimeoutSafety = false;
}
function _doSend(message, responseCallback) {
if (responseCallback) {
var callbackId = 'cb_'+(uniqueId++)+'_'+new Date().getTime();
responseCallbacks[callbackId] = responseCallback;
message['callbackId'] = callbackId;
}
sendMessageQueue.push(message);
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
}
function _fetchQueue() {
var messageQueueString = JSON.stringify(sendMessageQueue);
sendMessageQueue = [];
return messageQueueString;
}
function _dispatchMessageFromObjC(messageJSON) {
if (dispatchMessagesWithTimeoutSafety) {
setTimeout(_doDispatchMessageFromObjC);
} else {
_doDispatchMessageFromObjC();
}
function _doDispatchMessageFromObjC() {
var message = JSON.parse(messageJSON);
var messageHandler;
var responseCallback;
if (message.responseId) {
responseCallback = responseCallbacks[message.responseId];
if (!responseCallback) {
return;
}
responseCallback(message.responseData);
delete responseCallbacks[message.responseId];
} else {
if (message.callbackId) {
var callbackResponseId = message.callbackId;
responseCallback = function(responseData) {
_doSend({
handlerName:message.handlerName,
responseId:callbackResponseId,
responseData:responseData });
};
}
var handler = messageHandlers[message.handlerName];
if (!handler) {
console.log("WebViewJavascriptBridge: WARNING: no handler for message from ObjC:", message);
} else {
handler(message.data, responseCallback);
}
}
}
}
function _handleMessageFromObjC(messageJSON) {
_dispatchMessageFromObjC(messageJSON);
}
messagingIframe = document.createElement('iframe');
messagingIframe.style.display = 'none';
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
document.documentElement.appendChild(messagingIframe);
registerHandler("_disableJavascriptAlertBoxSafetyTimeout", disableJavscriptAlertBoxSafetyTimeout);
setTimeout(_callWVJBCallbacks, 0);
function _callWVJBCallbacks() {
var callbacks = window.WVJBCallbacks;
delete window.WVJBCallbacks;
for (var i=0; i<callbacks.length; i++) {
callbacks[i](WebViewJavascriptBridge);
}
}
})();