从UIWebView中以编程方式获取选定元素?

5

目前我正在使用webview展示这个样例网站,页面显示正常。

现在我想知道用户点击webview后选择了哪些数据。

为此,我可以使用UITapGestureRecognizer获取点击的CGPoint。

-(void)singleTap:(UIGestureRecognizer *)gestureRecognizer
{

    CGPoint touchPoint = [gestureRecognizer locationInView:myWebView];

    NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).toString()", touchPoint.x, touchPoint.y];

    NSString * tagName = [myWebView stringByEvaluatingJavaScriptFromString:js];

    NSLog(@"Selected Name: %@",tagName); 

}

// In log it is displaying [object SVGPathElement]

当用户选择第一个图表中的垂直条(例如1994/1995/1996)时,我希望能够获取确切的数据。

如何实现?


HTML页面在您的控制之下吗? - sergio
不,这不在我的控制范围内。但你仍然可以提出你的建议 :) - raaz
3个回答

2

您没有说明哪些方面的功能无法正常工作... 无论如何,我有几个建议:

  1. try with the following js in your tap handler:

    NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).innerHTML", touchPoint.x, touchPoint.y];
    
  2. when creating your tap gesture handler, specify a delegate for it (it can be your controller):

    tap1.delegate = self;
    
  3. in your controller (or web view delegate), define the following delegate method:

    - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:    (UIGestureRecognizer*)otherGestureRecognizer {
        return YES;
    }
    
  4. if you are using iOS 5, have a look at this article about a glitch in elementFromPoint.

通过这样做,我能够获取所选对象的精确HTML值。

请注意,这对于谷歌图片或其他以奇怪方式显示图像的网站效果不佳... - jjxtra

0
当用户在UIWebView上进行选择时,可以通过实现UIWebViewDelegate来拦截AJAX http请求。
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

方法。

然后您可以接受请求加载,阻止它,分析它,以任何您喜欢的方式处理它。


0
如果它们都是独立的DOM元素,你应该能够在JavaScript中监听touchstart事件,当你得到事件对象时,它应该有event.target,这将是用户单击的元素。然后你可以在JS中捕获所需的数据,然后将其发送回Objective-C。从JS获取数据到本地代码的最佳方法是使用UIWebView delegate,这应该对你有帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接