譯者:@coderyi9
本文翻譯自Marcus Westin的開源框架WebViewJavascriptBridge的readme,英文原文鏈接https://github.com/marcuswestin/WebViewJavascriptBridge.
WebViewJavascriptBridge是Obj-C和JavaScript通過UIWebViews/WebViews互通消息的一個iOS/OSX的橋梁. 如果你喜歡WebViewJavascriptBridge,你可能也想check outWebViewProxy.
Obj-C和JavaScript原理簡單說一下,Obj-C調用JavaScript很簡單,可以通過webview的stringByEvaluatingJavaScriptFromString:方法調用JavaScript代碼;JavaScript調用Obj-C,則是通過web view的代理方法shouldStartLoadWithRequest:來接收JavaScript的網絡請求從而實現調用。
正在使用WebViewJavascriptBridge的項目
有很多的公司和項目在使用WebViewJavascriptBridge.這個列表不完整,你可以隨意添加.
Facebook Messenger
Facebook Paper
Yardsale
EverTrue
Game Insight
Altralogica
Sush.io
Flutterby Labs
JD Media’s 鼎盛中華
Dojo4’s Imbed
CareZone
Hemlig
安裝& 例子 (iOS & OSX)
首先打開Example Apps文件夾.打開iOS或者OSX的工程然後點擊運行.
在你自己的工程中用WebViewJavascriptBridge:
1) 拖動 WebViewJavascriptBridge 文件夾到你的工程中.
在出現的對話框中, 取消 (我覺得應該是選中)”Copy items into destination group’s folder” 並且 選擇 “Create groups for any folders”
2) 引入頭文件並且申明一個屬性:
#import "WebViewJavascriptBridge.h" ... @property WebViewJavascriptBridge* bridge;
3) 實例化WebViewJavascriptBridge並且帶上一個UIWebView (iOS)或者WebView (OSX):
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"Received message from javascript: %@", data); responseCallback(@"Right back atcha"); }];
4) 首先從ObjC到javascript發送一些消息:
[self.bridge send:@"Well hello there"]; [self.bridge send:[NSDictionary dictionaryWithObject:@"Foo" forKey:@"Bar"]]; [self.bridge send:@"Give me a response, will you?" responseCallback:^(id responseData) { NSLog(@"ObjC got its response! %@", responseData); }];
5) 然後,看看javascript這邊:
function connectWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { callback(WebViewJavascriptBridge) } else { document.addEventListener('WebViewJavascriptBridgeReady', function() { callback(WebViewJavascriptBridge) }, false) } } connectWebViewJavascriptBridge(function(bridge) { /* Init your app here */ bridge.init(function(message, responseCallback) { alert('Received message: ' + message) if (responseCallback) { responseCallback("Right back atcha") } }) bridge.send('Hello from the javascript') bridge.send('Please respond to this', function responseCallback(responseData) { console.log("Javascript got its response", responseData) }) })
Contributors & Forks
Contributors: https://github.com/marcuswestin/WebViewJavascriptBridge/graphs/contributors
Forks: https://github.com/marcuswestin/WebViewJavascriptBridge/network/members
API 參考
ObjC API
[WebViewJavascriptBridge bridgeForWebView: (UIWebView/WebView*)webview handler:(WVJBHandler)handler]
[WebViewJavascriptBridge bridgeForWebView:
(UIWebView/WebView*)webview webViewDelegate:
(UIWebViewDelegate*)webViewDelegate handler:(WVJBHandler)handler]
給web view創建一個javascript的橋梁.
假如javascript需要一個反饋,那麼 WVJBResponseCallback 不能為 nil .
當然,通過 webViewDelegate:(UIWebViewDelegate*)webViewDelegate 你可以得到web view的生命周期事件.
例子:
[WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"Received message from javascript: %@", data); if (responseCallback) { responseCallback(@"Right back atcha"); } }] [WebViewJavascriptBridge bridgeForWebView:webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) { /* ... */ }];
[bridge send:(id)data]
[bridge send:(id)data responseCallback:(WVJBResponseCallback)responseCallback]
發送一個消息給javascript. 並且在發送消息成功後可以通過 responseCallback block做出一 些反應.
例子:
[self.bridge send:@"Hi"]; [self.bridge send:[NSDictionary dictionaryWithObject:@"Foo" forKey:@"Bar"]]; [self.bridge send:@"I expect a response!" responseCallback:^(id responseData) { NSLog(@"Got response! %@", responseData); }];
[bridge registerHandler:(NSString*)handlerName handler: (WVJBHandler)handler]
注冊一個叫做 handlerName 的handler. javascript能夠通過 WebViewJavascriptBridge.callHandler(“handlerName”) 調起這個handler.
例子:
[self.bridge registerHandler:@"getScreenHeight" handler:^(id data, WVJBResponseCallback responseCallback) { responseCallback([NSNumber numberWithInt:[UIScreen mainScreen].bounds.size.height]); }];
[bridge callHandler:(NSString*)handlerName data:(id)data]
[bridge callHandler:(NSString*)handlerName data:(id)data responseCallback:(WVJBResponseCallback)callback]
調起javascript叫做 handlerName的handler. 在調用 handler成功後可以通過responseCallback block做出反應.
例子:
[self.bridge callHandler:@"showAlert" data:@"Hi from ObjC to JS!"]; [self.bridge callHandler:@"getCurrentPageUrl" data:nil responseCallback:^(id responseData) { NSLog(@"Current UIWebView page URL is: %@", responseData); }];
定義 bundle
WebViewJavascriptBridge 要求 WebViewJavascriptBridge.js.txt 文件嵌入到web view來創建一個在JS這邊的橋梁.標准的實現是用 mainBundle 找到這個文件.如果你建立一個 靜態庫並且你把這個文件放在其他地方,你可以用下面的方法找 WebViewJavascriptBridge.js.txt 文件:
[WebViewJavascriptBridge bridgeForWebView:
(UIWebView/WebView*)webView webViewDelegate:
(UIWebViewDelegate*)webViewDelegate handler:(WVJBHandler)handler
resourceBundle:(NSBundle*)bundle
例子:
[WebViewJavascriptBridge bridgeForWebView:_webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"Received message from javascript: %@", data); } resourceBundle:[NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"ResourcesBundle" withExtension:@"bundle"]] ];
Javascript API
document.addEventListener(‘WebViewJavascriptBridgeReady’,
function onBridgeReady(event) { … }, false)
一直等待 WebViewJavascriptBridgeReady DOM 事件.
例子:
document.addEventListener('WebViewJavascriptBridgeReady', function(event) { var bridge = event.bridge // Start using the bridge }, false)
bridge.init(function messageHandler(data, response) { … })
初始化這個橋. 這會調起 ‘WebViewJavascriptBridgeReady’ 的事件handler.
這個 messageHandler 函數會接收通過ObjC的 [bridge send:(id)data] 和 [bridge send:(id)data responseCallback:(WVJBResponseCallback)responseCallback] 方法 發送的所有消息.
如果ObjC發送消息時有WVJBResponseCallback block,那麼可以通過response對象發送消息.
例子:
bridge.init(function(data, responseCallback) { alert("Got data " + JSON.stringify(data)) if (responseCallback) { responseCallback("Right back atcha!") } })
bridge.send(“Hi there!”)
bridge.send({ Foo:”Bar” })
bridge.send(data, function responseCallback(responseData) { …
})
給ObjC發送消息. 在發送成功後可以通過 responseCallback 函數做出反應.
例子:
bridge.send("Hi there!") bridge.send("Hi there!", function(responseData) { alert("I got a response! "+JSON.stringify(responseData)) })
bridge.registerHandler(“handlerName”, function(responseData) { … })
注冊一個叫做 handlerName 的handler. ObjC能夠通過 [bridge callHandler:”handlerName” data:@”Foo”] 和 [bridge callHandler:”handlerName” data:@”Foo” responseCallback:^(id responseData) { … }] 兩個方法調起這個handler.
例子:
bridge.registerHandler("showAlert", function(data) { alert(data) }) bridge.registerHandler("getCurrentPageUrl", function(data, responseCallback) { responseCallback(document.location.toString()) })
iOS4 支持 (包括 JSONKit)
注:iOS4支持尚未在V2 +測試.
WebViewJavascriptBridge 默認使用 NSJSONSerialization .如果你需要iOS 4的支持,你可以用JSONKit,並且增加 USE_JSONKIT 的預處理宏到你的工程中.