首页 > 代码库 > WebViewJavascriptBridge-Obj-C和JavaScript互通消息的桥梁
WebViewJavascriptBridge-Obj-C和JavaScript互通消息的桥梁
本文翻译自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非常easy,能够通过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的project然后点击执行.
在你自己的project中用WebViewJavascriptBridge:
1) 拖动 WebViewJavascriptBridge 目录到你的project中.
在出现的对话框中, 取消 (我认为应该是选中)”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 的预处理宏到你的project中.
WebViewJavascriptBridge-Obj-C和JavaScript互通消息的桥梁