Search code examples
javascriptiphonetagname

element.tagname doesn't return <a> on links


I'm programming an iPhone app that uses a little bit of javascript code for get the element for a point on UIWebView.

I have a bit of experience on iPhone, but no experience on javascript, I found that code on a tutorial (here)

// Javascript code
function MyAppGetHTMLElementsAtPoint(x,y) {
    var tags = ",";
    var e = document.elementFromPoint(x,y);
    while (e) {
        if (e.tagName) {
            tags += e.tagName + ',';
        }
        e = e.parentNode;
    }
    return tags;
}

// iPhone code
    NSString *tags = [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(x,y);"]]
    if ([tags rangeOfString:@",A,"].location != NSNotFound) {
        NSLog(@"Link found");
        ....
    }

The problem is that I have tested this code with, for example, a google search webpage, and I don't get the "Link found" log.

I think that it may be because a page is not whole HTML, but I cannot do anything more.

Thanks!!

PD: I have the same problem, but not on all the pages, with the IMG tag (maybe it's because of CSS)


Solution

  • As suggested by @JuanMendes, the problem was on the coordinates that the iPhone passes to the javascript function.

    // Not working code
    // Searches the location on the main view, that is the full screen
    CGPoint pt = [gestureRecognizer locationInView:self.view];
    
    // Working code
    // Searches the location only on the webView
    CGPoint pt = [gestureRecognizer locationInView:self.webView];
    

    Thanks for the people that have help me with this, and especially for @JuanMendes