在Obj-C 和 WKWebView, UIWebView 中的 Javascript之間傳送信息的橋樑。javascript
項目地址java
<script> window.onerror = function(err) { log('window.onerror: ' + err) } //下面的方法是必備 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) } setupWebViewJavascriptBridge(function(bridge) { var uniqueId = 1; //打印方法 function log(message, data) { var log = document.getElementById('log') var el = document.createElement('div') el.className = 'logLine' el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data) if (log.children.length) { log.insertBefore(el, log.children[0]) } else { log.appendChild(el) } } //JS 註冊處理,名字需與 ObjC 一致 bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) { log('ObjC called testJavascriptHandler with', data) var responseData = { 'Javascript Says': 'Right back atcha!' } log('JS responding with', responseData) responseCallback(responseData) }) document.body.appendChild(document.createElement('br')) var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button')) callbackButton.innerHTML = 'Fire testObjcCallback' callbackButton.onclick = function(e) { // 點擊按鈕事件 e.preventDefault(); log('JS calling handler "testObjcCallback"'); // JS 向 ObjC 傳數據的方式,callHandler(方法標識符, 數據, 回調) bridge.callHandler('testObjcCallback', { 'foo': 'bar' }, function(response) { log('JS got response', response); }) } }) </script>
引入頭文件git
#import "WebViewJavascriptBridge.h"
聲明變量github
@property WebViewJavascriptBridge* bridge;
實現方法web
if (_bridge) { return; } UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webView]; [WebViewJavascriptBridge enableLogging]; _bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; [_bridge setWebViewDelegate:self]; [_bridge callHandler:@"testJavascriptHandler" data:@{@"foo":@"before ready"}]; [_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"testObjcCallback called: %@", data); NSString *strDD = [NSString stringWithFormat:@"hello world: %@",data]; responseCallback(strDD); }];