项目介绍:
WebViewJavascriptBridge是一个iOS/OSX桥梁,连接了Obj-C与UIWebViews/WebViews之间的传送信息。
安装(iOS&OSX)
用CocoaPods安装
将如下加入到你的podfile,然后运行 pod install 去安装
`pod 'WebViewJavascriptBridge', '~> 5.0'`
手动安装
将 WebViewJavascriptBridge 文件夹拖拽到你的项目中。
使用方法
1.import头文件,声明属性
#import "WebViewJavascriptBridge.h"
@property WebViewJavascriptBridge* bridge;
2.整合WebViewjavascriptBridge与UIWebView或者WebView
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
3,在ObjC注册一个处理器,然后调用一个JS处理器
[self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"ObjC Echo called with: %@", data); responseCallback(data);
}];
[self.bridge callHandler:@"JS Echo" responseCallback:^(id responseData) { NSLog(@"ObjC received response: %@", responseData);
}];
4.复制粘贴 setupWebViewJavascriptBridge 到你的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 = 'wvjbscheme://__BRIDGE_LOADED__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
5.最后,调用 setupWebViewJavascriptBridge ,然后使用注册处理器与调用ObjC处理器的桥接:
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)
})
})
https://github.com/marcuswestin/WebViewJavascriptBridge