Thursday 11 June 2009

UIWebView doesn't open target="_blank" links.

If you are using UIImageView to display external webpages, you may come across an issue where certain links don't fire UIWebViewNavigationTypeLinkClicked events. This happens when the link has the target="_blank" attribute.

To work around this problem you can inject some javascript after the page load to remove this attribute from all the links:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
        NSString *js = @"\
        var d = document.getElementsByTagName('a');\
        for (var i = 0; i < d.length; i++) {\
            if (d[i].getAttribute('target') == '_blank') {\
                d[i].removeAttribute('target');\
            }\
        }\
        ";

        [webView stringByEvaluatingJavaScriptFromString:js];
}

10 comments:

  1. Brilliant, thanks! -Jacob

    ReplyDelete
  2. You are a genius!! What a find! I was struggling to find a solution and it never crossed my mind to use an actual web technology such as Javascript to solve the problem.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. GREAT!!!! That was exactly what I was looking for!!

    ReplyDelete
  5. Very useful! Thanks for sharing.

    ReplyDelete
  6. This worked amazingly! Thanks very much.

    ReplyDelete
  7. Great – I must say! I am impressed with your website and I had no trouble navigating through all tabs. The information you shared with us is really fantastic and very useful. I feel as you know what I wanted. Reasonably unusual. Excellent task.

    ReplyDelete
  8. This is exactly what I needed - thanks very much.

    ReplyDelete
  9. I have read your blog its very attractive and impressive. I like it your blog.
    appvn
    kissanime alternatives

    ReplyDelete
  10. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. Martin Zhao

    ReplyDelete