简体   繁体   English

在Safari中打开其他网站的WKWebView链接

[英]Open WKWebView links for other websites in Safari

I have an app that has a wkwebview. 我有一个带有wkwebview的应用程序。 What I need help with is when a user clicks on a link inside the webview, it opens up in Safari. 我需要帮助的是,当用户单击Web视图内的链接时,它会在Safari中打开。 But, if they click on a link with the same domain, it opens in the webview. 但是,如果他们单击具有相同域的链接,则会在Web视图中打开该链接。

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. 如果Webview打开apple.com,并且用户单击打开apple.com/iphone的链接,我希望它在Webview内部打开。 But, if they click on a link that opens google.com, I want it to open in the safari app. 但是,如果他们单击打开google.com的链接,我希望它在野生动物园应用程序中打开。 Can you give me some code so I can implement this? 您能给我一些代码以便我实现吗?

(this is an iOS app using swift 3) (这是使用Swift 3的iOS应用)

In your WKNavigationDelegate implement webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) . WKNavigationDelegate实现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. 如果不是,则通过UIApplication.shared.open(url)打开链接,并使用.cancel执行决策处理程序-这样该链接不会加载到您的Web视图中。 Otherwise just allow... 否则就允许...

Quick and dirty version would be (Swift 4): 快速而肮脏的版本是(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)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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