How to open target="_blank" links in WKWebView in iOS

nemecek_f

Filip Němeček

Posted on January 31, 2020

How to open target="_blank" links in WKWebView in iOS

If you ever worked with WKWebView in your iOS application you may have noticed, that some links just don’t work. Meaning nothing happens when you click them. This post exaplains why WKWebView does not open some links and what to do about it.

The culprit is HTML attribute target set to value _blank which is used to signal links that should be opened in new tab instead of the current one.

<a href="dev.to" target="_blank" >Link</a>
Enter fullscreen mode Exit fullscreen mode

However if you have basic WKWebView setup, these links just don’t work.
The fix is hidden inside WKUIDelegate, more specifically in this method:

webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView?
Enter fullscreen mode Exit fullscreen mode

It is pretty long and automatically called whenever user is trying to open link from WKWebView.

It is there to give you opportunity to create new screen/tab in your application to provide user with same behavior as Safari or any other browsers.

You don’t have to implement this and still have working _blank links with this implementation:

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if let frame = navigationAction.targetFrame,
            frame.isMainFrame {
            return nil
        }
        webView.load(navigationAction.request)
        return nil
}
Enter fullscreen mode Exit fullscreen mode

You first check, whether the targetFrame is main frame, meaning your current WKWebView. If so, then do nothing and return. If not, you can simply load this request in your current instance and once again return nil.

Of course, don’t forget to set the WKUIDelegate otherwise this method won’t be called.

 webView.uiDelegate = self
Enter fullscreen mode Exit fullscreen mode

And that is all!

This is also published on my blog where you can check other Swift & iOS articles.

Is anything not clear? Do you want more information? Ask in the comments and I will do my best to help you. Thanks for reading!

Scan it - wide banner

Need to focus on your iPhone? Get free WebBlock app for scheduled website blocking from the App Store!

💖 💪 🙅 🚩
nemecek_f
Filip Němeček

Posted on January 31, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related