Skip to content

Instantly share code, notes, and snippets.

@irace
Created September 10, 2012 02:51
Show Gist options
  • Star 49 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save irace/3688560 to your computer and use it in GitHub Desktop.
Save irace/3688560 to your computer and use it in GitHub Desktop.
JavaScript/native bridge for iOS's UIWebView
- (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;
}
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'});
@Dan2552
Copy link

Dan2552 commented Sep 11, 2014

👍

@OlofT
Copy link

OlofT commented Sep 16, 2014

Nice!

@honasassa
Copy link

Nice work and it works well in iOS8, but i think this code is a bit tricky.. hmmm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment