轉自:http://www.cnblogs.com/YouXianMing/archive/2014/05/20/3738317.html
https://github.com/marcuswestin/WebViewJavascriptBridge
核心的地方:
UIWebView在加載完網頁之後,通過方法stringByEvaluatingJavaScriptFromString:來讓這個webView執行js腳本,之後想幹啥幹啥.
注意:必須是加載完之後!
使用
下載源碼拖入工程.
使用一個本地的html文件.
<!doctype html> <html><head> <style type='text/css'> html { font-family:Helvetica; color:#222; } h1 { color:steelblue; font-size:24px; margin-top:24px; } button { margin:0 3px 10px; font-size:12px; } .logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; } </style> </head><body> <h1>WebViewJavascriptBridge Demo</h1> <!--腳本開始的地方--> <script> window.onerror = function(err) { log('window.onerror: ' + err) } <!--申明方法--> function connectWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { callback(WebViewJavascriptBridge) } else { document.addEventListener('WebViewJavascriptBridgeReady', function() { callback(WebViewJavascriptBridge) }, false) } } <!--激活方法--> connectWebViewJavascriptBridge(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 + (data ? ':<br/>' + JSON.stringify(data) : '') if (log.children.length) { log.insertBefore(el, log.children[0]) } else { log.appendChild(el) } } bridge.init(function(message, responseCallback) { log('JS got a message', message) var data = { 'Javascript Responds':'Wee!' } log('JS responding with', data) responseCallback(data) }) 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) }) <!--創建一個按鈕--> var button = document.getElementById('buttons').appendChild(document.createElement('button')) button.innerHTML = 'Send message to ObjC' button.onclick = function(e) { e.preventDefault() <!--此處是你傳參數的地方--> var data = 'YouXianMing' log('JS sending message', data) bridge.send(data, function(responseData) { log('JS got response', responseData) }) } document.body.appendChild(document.createElement('br')) }) <!--腳本結束的地方--> </script> <div id='buttons'></div> <div id='log'></div> </body></html>
RootViewController代碼如下:
// // RootViewController.m // WebViewJavascriptBridge // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "RootViewController.h" #import "WebViewJavascriptBridge.h" @interface RootViewController ()<UIWebViewDelegate> @property (nonatomic, strong) UIWebView *webView; @property (nonatomic, strong) WebViewJavascriptBridge *bridge; @end #define BUNDLE_FILE(fileName) [[NSBundle mainBundle] pathForResource:fileName ofType:nil]; #define HTML_STRING(htmlPath) [NSString stringWithContentsOfFile:htmlPath \ encoding:NSUTF8StringEncoding error:nil] #define FILE_URL(path) [NSURL fileURLWithPath:path] @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; // 獲取本地html文件 NSString *htmlPath = BUNDLE_FILE(@"demo.html"); // 初始化UIWebView並添加進view中 _webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; [_webView loadHTMLString:HTML_STRING(htmlPath) baseURL:FILE_URL(htmlPath)]; [self.view addSubview:_webView]; // 讓UIWebView執行腳本並監聽回調 _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView handler:^(id data, WVJBResponseCallback responseCallback) { // 監聽回調 NSLog(@"%@", data); }]; } @end
執行效果如下:
分析
WebViewJavascriptBridge.m 的源碼裏面有寫着讓webView執行js腳本的地方哦.
其實,我們只需要能夠從UIWebView獲取到值就行了,我們纔不需要把值傳遞給UIwebView呢,有了這個UIWebView給iOS傳值的功能,基本上能滿足我們大部分的需求了哦.
最後,我將html頁面進行修改,精簡到大家能看懂爲止:).
demo.html
<!doctype html> <html><head> <style type='text/css'> html { font-family:Helvetica; color:#222; } h1 { color:steelblue; font-size:24px; margin-top:24px; } button { margin:0 3px 10px; font-size:12px; } .logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; } </style> </head><body> <h1>UIWebView與iOS直接交互</h1> <!--腳本開始的地方--> <script> <!--申明方法--> function connectWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { callback(WebViewJavascriptBridge) } else { document.addEventListener('WebViewJavascriptBridgeReady', function() { callback(WebViewJavascriptBridge) }, false) } } <!--激活方法--> connectWebViewJavascriptBridge(function(bridge) { <!--創建一個按鈕--> var button = document.getElementById('buttons').appendChild(document.createElement('button')) button.innerHTML = '給iOS發送信息' <!--按鈕點擊事件的實現--> button.onclick = function(e) { e.preventDefault() <!--此處是你傳參數的地方--> var data = 'YouXianMing - Just so easy :)' <!--使用bridge中的send發送數據--> bridge.send(data, function(responseData) { }) } document.body.appendChild(document.createElement('br')) }) <!--腳本結束的地方--> </script> <div id='buttons'></div> <div id='log'></div> </body></html>
以下是修改後的執行效果:
附錄:
WebViewJavascriptBridge與UIWebView交互原理