35

Is there a way to get a callback to objective-c when a certain event has been detected in a UIWebView? Can Javascript send a callback to Objective-C?

Adi
  • 5,089
  • 6
  • 33
  • 47
LK.
  • 4,499
  • 8
  • 38
  • 48

2 Answers2

31

Update - don't use UIWebView anymore. Use WKWebView, or better yet (if it fits your needs and you're building for iOS 9), a Safari View Controller.

But if you must use UIWebView, in your UIWebView delegate, provide an implementation for webView:shouldStartLoadWithRequest:navigationType:

In your HTML or Javascript files, add functions that send URLs to a custom scheme (for readability purposes, the custom scheme isn't required). All the URLs sent will be passed to your Objective-C method implementation, and then you can do what you'd like.

bpapa
  • 21,409
  • 25
  • 99
  • 147
  • Is there any other option for achieving this? (for example, with newer iOS versions)? – lysergic-acid Feb 25 '14 at 12:48
  • 1
    @lysergic-acid I haven't really messed with WebViews in awhile, but I'd imagine no since this is actually a pretty nice solution. Unless you could somehow tie a block to JS events (check the UIWebView docs). iOS 7 did add JavaScriptCore but I'm not sure that it would be helpful here. – bpapa Feb 25 '14 at 16:12
31

Just to illustrate the solution by "bpapa" with actual code:

WARNING: untested code

Implement this method in the UIWebView's delegate...

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
    if ( [[[inRequest URL] scheme] isEqualToString:@"callback"] ) {

        // Do something interesting...

        return NO;
    }

    return YES;
}

...then put a link in the webwieb like this:

<a href="callback:whatever">Click me</a>

And it should activate your callback-code. Obviously, you could trigger it with a javascript instead of a plain link.

geon
  • 8,128
  • 3
  • 34
  • 41
  • 3
    I think the scheme does not contain the colon. It would be just @"callback". And for the comparison, I think you should use `- (BOOL)isEqualToString:(NSString *)aString;` – mkko Dec 17 '11 at 11:17
  • Is there any limitation for using this approach? am i limited in the data that i can pass in the URL, for example? (length, chars, or any other limitation?) – lysergic-acid Feb 25 '14 at 13:17