views:

319

answers:

2

Hey guys,

How can I figure out which word is at the point where the user tapped on a UIWebView?

I am able to detect the CGPoint for the tap (subclassing UIWindow like this), and I can actually get the DOM element on that point using javascript.

But I know very little of javascript and DOM to figure out how can I actually get which word the user tapped on.

Is that possible? Here's what I have right now:

int scrollPosition = [[webView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];
NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", point.x, point.y+scrollPosition];
NSString *value = [webView stringByEvaluatingJavaScriptFromString:js];

NSLog(@"element: %@", value);
+1  A: 

I am not sure how you would get the exact word, but, I believe you can get the text in an element iterating through it's children and looking for elements with nodeType 3 which is text.

AK
I ended up wrapping each word on a <span> tag and using the element node's textContent property to get which word was tapped.
leolobato
A: 

There was a method which I can't locate right now, which let you communicate info from UIWebView back "up" to the containing Cocoa app with some Javascript bridge. So I'd attach "click" handlers to all the elements of interest in the UIWebView, and fire some message to parent container with this magical bridge.

This assumes that you control the contents of UIWebView and can inject the needed Javascript. If this needs to work with any webpage, it's harder.

Jaanus
If I'll need to add links to every word I'd need tapping on, I'd rather wrap each one on a separate <span> tag. Detecting a tap the way I'm doing on the question, I think, is lighter and the resulting HTML will be much smaller. Thanks!
leolobato