iosswiftuiwebviewwkwebviewwkwebviewconfiguration

How to get headers from WKWbView finish loads


I am using WKWebView in app & i am looking for getting all headers from wkwebview in finish loads method webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { Just like in UIWebView

func webViewDidFinishLoad(_ webView: UIWebView) {
        print("Finished loads---", webView.request?.allHTTPHeaderFields)
    }

How can we achieve that in WKWebView ?


Solution

  • You need to set your view controller as the WKWebView Navigation Delegate WKNavigationDelegate and implement its decidePolicyFor method:

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

    Try like this:


    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields ?? [:]
        for (key, value) in allHTTPHeaderFields {
            print("key:", key, "value:", value)
        }
        
        if navigationAction.navigationType == .linkActivated  {
            if let url = navigationAction.request.url,
                let host = url.host, !host.hasPrefix("www.google.com"),
                UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
                print(url)
                print("Redirected to browser. No need to open it locally")
                decisionHandler(.cancel)
            } else {
                print("Open it locally")
                decisionHandler(.allow)
            }
        } else {
            print("not a user click")
            decisionHandler(.allow)
        }
    }