-
Notifications
You must be signed in to change notification settings - Fork 208
Setup a WebViewJavascriptBridge
Adding a WebViewJavascriptBridge to you MacGap application makes sending information to and from the native Objective-C code and the javascript very simple.
To start, download the latest version of the bridge from https://github.com/marcuswestin/WebViewJavascriptBridge.
Within the repo folder, find the WebViewJavascriptBridge
folder and drag it onto your project in Xcode.
In the dialog that appears, uncheck "Copy items into destination group's folder" and select "Create groups for any folders".
Within the ContentView.h
file, import the header file and declare the bridge property:
#import "WebViewJavascriptBridge.h"
//...
@interface ContentView : NSView {
IBOutlet WebView* webView;
WebViewDelegate* delegate;
}
//...
@property (retain) WebViewJavascriptBridge* bridge;
@end
Within the ContentView.m
file, synthesize the bridge property.
@synthesize webView, delegate, bridge;
And add a new method to create the bridge.
- (void) createBridge {
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"message from JS: %@", data);
//`data` will be any message sent via the bridge from javascript.
//Do something with it…
}];
}
To start the bridge, call the createBridge
method at the end of the awakeFromNib
method.
- (void) awakeFromNib
{
//...
//start the bridge
[self createBridge];
}
Now in your javascript, use the following to connect to the bridge and listen for data sent from the native code. I’ve wrapped the code in a Bridge
object to keep it all neat and tidy.
var Bridge = {
init: function() {
this.connectBridge(this.listener);
},
connectBridge: function connectBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
}
else {
document.addEventListener('WebViewJavascriptBridgeReady', function() {
callback(WebViewJavascriptBridge);
}, false);
}
},
listener: function listener(bridge) {
//the bridge.init function receives all messages sent from Obj-C
bridge.init(function(message, responseCallback) {
console.log('Message from inside: ', message);
});
},
send: function send(data, callback) {
if(callback) {
WebViewJavascriptBridge.send(data, callback);
}
else {
WebViewJavascriptBridge.send(data);
}
}
};
Finally, back in the ContentView.m
file, use the following to send data to the javascript application:
NSDictionary *sendData = @{
@"messageType": @"theButtonWasClicked",
@"messageData": @true
};
[self.bridge send:sendData];
rtat.net