Ken
Ken

Reputation: 31161

Touches in a UIWebView

I'm developing an iOS app with a UIWebView instance.

If the user touches an object in a webpage shown by the web view, how can I extract metadata regarding the object touched (such as an "id" for an HTML element) over in Objective C land?

[I'm not interested in whether the web view was touched or not, I'm only interested in what part of the page was touched and being able to act on this.]

Upvotes: 1

Views: 322

Answers (1)

Nick Lockwood
Nick Lockwood

Reputation: 40995

You probably need to do this in JavaScript land. In your webview set up some javascript to monitor the click (e.g. element.onclick = function() { ... }, or use jQuery if that's easier).

Now you can call out to the native code in your app by using a made up url and then intercepting it using the webview delegate, e.g.

//in your web page, in javascript

myDiv.onclick = function() { document.location.href = 'http://madeupdomain/' + this.id};

//webview delegate in cocoa

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *URL = [request URL];
    NSString *host = URL.host;
    if ([host isEqualToString:@"madeupdomain"])
    {
        NSString *theDivID = URL.path;
        //now do something based on the div id value

        return NO;
    }
    return YES;
}

This is essentially how frameworks like PhoneGap communicate between the webview and the native code.

Upvotes: 3

Related Questions