简体   繁体   中英

Javascript in UIWebView callback to C/Objective-C

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM