停止导航WKWebview

 收藏

这是我的情况:

我在WKWebView中有一个视图控制器。该Web视图以页面“ A”开头。在此页面中,有一些链接(href),我希望其中的某些链接必须在外部浏览器中打开。

因此,我设置了WKWebView委托:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        if let url = webView.url?.absoluteString
        {

                if(self.isExternalURL(url))
                {
                    let urlT = URL(string: url)!
                    decisionHandler(.cancel)
                    UIApplication.shared.open(urlT, options: [:], completionHandler: nil)
                }
                else
                {
                    decisionHandler(.allow)
                }
         }
         else
         {
                decisionHandler(.allow)
         }
}

private func isExternalURL(url:String) -> Bool
{
    //......check link
}

我的问题是,如果我选择一个外部链接,则会打开外部浏览器,但Web视图不会保留在页面A上,但是它还会加载外部链接,而我希望它保留在页面A上。

我不知道为什么

回复
  • 苍涼 回复

    You can try to use webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)

    func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    
            if let url = navigationAction.request.url?.absoluteString
            {
                if self.isExternalURL(url)
                {
                   webView.stopLoading()
                    UIApplication.shared.open(navigationAction.request.url, options: [:], completionHandler: nil)
                }
    
            }
    
        }
    

  • 薄荷绿 回复

    You should use navigationAction.request.url instead of webView.url

    • webView.url - Already loaded url
    • navigationAction.request.url - New url to load

    更改

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url?.absoluteString
        {
            if self.isExternalURL(url)
            {
                decisionHandler(.cancel)
                UIApplication.shared.open(navigationAction.request.url, options: [:], completionHandler: nil)
            }
            else
            {
                decisionHandler(.allow)
            }
        }
        else
        {
            decisionHandler(.allow)
        }
    }