iFunnyVlogger
iFunnyVlogger

Reputation: 467

Open WKWebView links for other websites in Safari

I have an app that has a wkwebview. What I need help with is when a user clicks on a link inside the webview, it opens up in Safari. But, if they click on a link with the same domain, it opens in the webview.

For example. If the webview opens up apple.com and a user click on a link that opens up apple.com/iphone I want it to open inside the webview. But, if they click on a link that opens google.com, I want it to open in the safari app. Can you give me some code so I can implement this?

(this is an iOS app using swift 3)

Upvotes: 4

Views: 5819

Answers (1)

orschaef
orschaef

Reputation: 1337

In your WKNavigationDelegate implement webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void). There you can check if the host of the selected link is the same like in your initial request. If not, you open the link via UIApplication.shared.open(url) and execute the decision handler with .cancel - so the link does not load in your web view. Otherwise just allow...

Quick and dirty version would be (Swift 4):

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  if navigationAction.navigationType == .linkActivated  {
    if let url = navigationAction.request.url, 
       originalHost != url.host, UIApplication.shared.canOpenURL(url) {
      UIApplication.shared.open(url)
      decisionHandler(.cancel)
    } else {
      decisionHandler(.allow)
    }
  } else {
    decisionHandler(.allow)
  }
}

Upvotes: 17

Related Questions