https://github.com/marcuswestin/WebViewJavascriptBridge
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)
}
Finally, call setupWebViewJavascriptBridge and then use the bridge to register handlers and call ObjC handlers:
setupWebViewJavascriptBridge(function(bridge) {
/* Initialize your app here */
bridge.registerHandler('JS Echo', function(data, responseCallback) {
console.log("JS Echo called with:", data)
responseCallback(data)
})
bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
console.log("JS received response:", responseData)
})
})
github地址如上
工作中用到了这个桥接,出现了很多问题,
首先,初始化了这个函数之后,然后调用这个函数,调用ios端定义的handler或者js 注册自己的handler,
但是好像不可以写多个该函数的调用,否则所有写的交互不生效。
那么我如果想调用ios定义的多个函数,只能写在一个调用里,罗列多个
bridge.registerHandler
和
bridge.callHandler来写了。
目前还是出现了个别交互不生效的问题。
registerHandler 就是在网页端定义一个函数,获取后端返回的相应参数,后端调用使用
callHandler 就是在ios端定义一个函数,网页端调用,传过去相应参数。