Github - WebViewJavascriptBridge
An iOS/OSX bridge for sending messages between Obj-C and JavaScript in UIWebViews/WebViews
简单优雅的实现 Objective-C 与 JavaScript 的交互。
集成指南
- Cocoapods
pod 'WebViewJavascriptBridge'
- 手动
下载WebViewJavascriptBridge
后直接把WebViewJavascriptBridge
文件夹拖到目标工程相关目录即可。
使用指南
- 导入头文件
#import "WebViewJavascriptBridge.h"
...
@property WebViewJavascriptBridge* bridge;
- 初始化
WebViewJavascriptBridge
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
- 开始交互
//js call oc handle
[self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"ObjC Echo called with: %@", data);
responseCallback(data);
}];
//oc call js handle
[self.bridge callHandler:@"JS Echo" data:nil responseCallback:^(id responseData) {
NSLog(@"ObjC received response: %@", responseData);
}];
- 添加下面代码到相应的 JavaScript
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)
}
- 最后,在 JavaScript 中与 oc 进行类似的交互
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)
})
})