简体   繁体   中英

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)

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)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM