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];
}

6 comments:

  1. AnonymousJun 16, 2009 12:44 PM
    Brilliant, thanks! -Jacob
    ReplyDelete
  2. BrotherJul 7, 2009 09:22 AM
    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. Ben ThompsonAug 18, 2009 09:56 PM
    This comment has been removed by the author.
    ReplyDelete
  4. JimmySep 24, 2009 02:42 AM
    GREAT!!!! That was exactly what I was looking for!!
    ReplyDelete
  5. AnonymousNov 22, 2009 08:47 PM
    Very useful! Thanks for sharing.
    ReplyDelete
  6. AnonymousOct 7, 2010 08:47 AM
    This worked amazingly! Thanks very much.
    ReplyDelete