Get the current full URL for WKWebView

前端 未结 3 933
误落风尘
误落风尘 2020-12-15 03:47

Is there a way to get the FULL URL loaded by a WKWebView for every request?

webView:didFinishNavigation:

Works only for

相关标签:
3条回答
  • 2020-12-15 04:27

    This is Yuichi Kato's answer for Swift 4. It retrieves the full URL from the request property of the navigation action in the webView(_:decidePolicyFor:decisionHandler:) method of WKNavigationDelegate.

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let urlStr = navigationAction.request.url?.absoluteString {
            //urlStr is what you want
        }
    
        decisionHandler(.allow)
    }
    

    Don't forget to conform your class to WKNavigationDelegate and set your web view's delegate accordingly:

    class WebViewController: UIViewController, WKNavigationDelegate
    
    [...]
    
    webView.navigationDelegate = self
    
    0 讨论(0)
  • 2020-12-15 04:35

    First, I think you are confusing NSURL and NSURLRequest. The first is readily accessibly via webView.URL and it does actually give you the full URL of whatever was loaded. Assuming that where you say URL you mean NSURL.

    If that is not what you meant, for example if you wanted to see the redirect chain or the response headers, then I'm afraid the answer is that you cannot get to tht specific information via the WKWebView.

    You will have to fall back to UIWebView where you can intercept requests relatively easily and see the full request/response.

    0 讨论(0)
  • 2020-12-15 04:45

    You can get URL for a newly requested Webpage by "navigationAction.request.URL" in decidePolicyForNavigationAction delegate method.

    func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
       if let urlStr = navigationAction.request.URL?.absoluteString{
          //urlStr is what you want, I guess.
       }
       decisionHandler(.Allow)
    }
    
    0 讨论(0)
提交回复
热议问题