Bridge between WebViewJavascriptBridge-Obj-C and JavaScript
.
WebViewJavascriptBridge is a bridge between Obj-C and JavaScript to communicate messages through UIWebViews/WebViews on iOS/OSX. If you like WebViewJavascriptBridge, you may also want to check outWebViewProxy.
Obj-C and JavaScript: the calling of JavaScript by Obj-C is simple. You can use stringByEvaluatingJavaScriptFromString of webview to call JavaScript code. JavaScript calls Obj-C, the web view proxy method shouldStartLoadWithRequest is used to receive JavaScript Network requests for calling.
A project using WebViewJavascriptBridge
There are many companies and projects using WebViewJavascriptBridge. This list is incomplete and you can add it at will.
Facebook Messenger
Facebook Paper
Yardsale
EverTrue
Game Insight
Altralogica
Sush. io
Flutterby Labs
JD Media's flourishing in China
Dojo4's Imbed
CareZone
Hemlig
Installation & example (iOS & OSX)
First open the Example Apps folder. Open the iOS or OSX project and click Run.
Use WebViewJavascriptBridge in your project:
1) drag the WebViewJavascriptBridge folder to your project.
In the displayed dialog box, cancel (I think it should be selected) "Copy items into destination group's folder" and select "Create groups for any folders"
2) introduce the header file and declare an attribute:
#import WebViewJavascriptBridge.h ... @property WebViewJavascriptBridge* bridge;
3) instantiate WebViewJavascriptBridge and bring a UIWebView (iOS) or WebView (OSX ):
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {NSLog(@Received message from javascript: %@, data);responseCallback(@Right back atcha);}];
4) First, send some messages from ObjC to 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) then, look at the javascript side:
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 reference
ObjC API
[WebViewJavascriptBridge bridgeForWebView: (UIWebView/WebView *) webview handler :( WVJBHandler) handler]
[WebViewJavascriptBridge bridgeForWebView:
(UIWebView/WebView *) webview webViewDelegate:
(UIWebViewDelegate *) webViewDelegate handler :( WVJBHandler) handler]
Create a javascript bridge for web view.
If javascript requires a feedback, WVJBResponseCallback cannot be nil.
Of course, you can use webViewDelegate :( UIWebViewDelegate *) to get the web view lifecycle events.
Example:
[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]
Send a message to javascript. After the message is successfully sent, you can use the responseCallback block to make some responses.
Example:
[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]
Register a handler. javascript called handlerName to call this handler through WebViewJavascriptBridge. callHandler ("handlerName.
Example:
[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]
Call the handler called handlerName in javascript. After the handler is successfully called, you can use the responseCallback block to respond.
Example:
[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);}];
Define bundle
WebViewJavascriptBridge requires that the WebViewJavascriptBridge.js.txt file be embedded in the web view to create a bridge on the JS side. the standard implementation is to use mainBundle to find this file. if you create a static library and place the file elsewhere, you can use the following method to find the WebViewJavascriptBridge.js.txt file:
[WebViewJavascriptBridge bridgeForWebView:
(UIWebView/WebView *) webView webViewDelegate:
(UIWebViewDelegate *) webViewDelegate handler :( WVJBHandler) handler
ResourceBundle :( NSBundle *) bundle
Example:
[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)
Wait for the WebViewJavascriptBridgeReady DOM event.
Example:
document.addEventListener('WebViewJavascriptBridgeReady', function(event) {var bridge = event.bridge// Start using the bridge}, false)
Bridge. init (function messageHandler (data, response ){... })
Initialize this bridge. This will call the 'webviewjavascriptbridgeready' event handler.
This messageHandler function will receive all messages sent through the [bridge send :( id) data] and [bridge send :( id) data responseCallback :( WVJBResponseCallback) responseCallback] Methods of ObjC.
If the ObjC sends a message with the WVJBResponseCallback block, the message can be sent through the response object.
Example:
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 ){...
})
Send messages to ObjC. After successful sending, you can use the responseCallback function to respond.
Example:
bridge.send(Hi there!)bridge.send(Hi there!, function(responseData) {alert(I got a response! +JSON.stringify(responseData))})
Bridge. registerHandler ("handlerName", function (responseData ){... })
Register a handler named handlerName. objC can use [bridge callHandler: "handlerName" data: @ "Foo"] and [bridge callHandler: "handlerName" data: @ "Foo" responseCallback: ^ (id responseData ){... }] Two Methods call the handler.
Example:
bridge.registerHandler(showAlert, function(data) { alert(data) })bridge.registerHandler(getCurrentPageUrl, function(data, responseCallback) {responseCallback(document.location.toString())})
IOS4 support (including JSONKit)
Note: iOS4 support has not been tested in V2 +.
WebViewJavascriptBridge uses NSJSONSerialization by default. If you need iOS 4 support, you can use JSONKit and add the USE_JSONKIT preprocessing macro to your project.