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

633 Views Asked by At

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)

3

There are 3 best solutions below

2
On BEST ANSWER

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

1
On

Have you tried logging e.tagName each time? Then you can see what you're getting for the links.

5
On

Some modes of XHTML return tagName as you put it in the source, so it could be lower cased. Try calling

tags += e.tagName.toUpperCase() + ',';

If that's not the problem, what does the tags string contain?

Completely unrelated suggestion

Arrays are the best way to create comma separated lists

function MyAppGetHTMLElementsAtPoint(x,y) {
    var tags = [];
    var e = document.elementFromPoint(x,y);
    while (e) {
        if (e.tagName) {
            tags.push(e.tagName);
        }
        e = e.parentNode;
    }
    return tags.join(',');
}

I provided a JSFiddle http://jsfiddle.net/cgpVk/1/ that proves the function is working fine. You're probably not passing it the right coordinates