public
Last active

JavaScript/native bridge for iOS's UIWebView

  • Download Gist
BIWebViewDelegate.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSString *urlString = [[request URL] absoluteString];
if ([urlString hasPrefix:@"js:"]) {
NSString *jsonString = [[[urlString componentsSeparatedByString:@"js:"] lastObject]
stringByReplacingPercentEscapes];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id parameters = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers
error:&error];
if (!error) {
// TODO: Logic based on parameters
}
}
return NO;
}
bridge.js
JavaScript
1 2 3 4 5 6 7 8 9 10
var sendObjectMessage = function(parameters) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'js:' + JSON.stringify(parameters));
 
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
};
 
sendObjectMessage({name: 'Bryan', company: 'Tumblr'});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.