如何从 WKWebView 完成加载中获取 headers

How to get headers from WKWbView finish loads

我在应用程序中使用 WKWebView 并且我正在寻找从 wkwebview 中获取所有 headers 完成加载方法 webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { 就像在 UIWebView[=16= 中一样]

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

我们如何才能在 WKWebView 中实现这一目标?

您需要将视图控制器设置为 WKWebView 导航委托 WKNavigationDelegate 并实现其 decidePolicyFor 方法:

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

这样试试:


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

使用WKWebViewwebView(_:decidePolicyFor:decisionHandler:)

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    // MARK: - IBOutlet
    @IBOutlet weak var webView: WKWebView!
    
    
    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.navigationDelegate = self
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        let urlStr = "https://www.google.com/"
        if let url = URL(string: urlStr) {
            let request = URLRequest(url: url)
            webView.load(request)
            //webView.allowsBackForwardNavigationGestures = false
            //webView.navigationDelegate = self
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let request = navigationAction.request
        if let host = navigationAction.request.url?.host {
            if host == "www.google.com" {
                if let headers = request.allHTTPHeaderFields {
                    print("Google Headers: \(headers)")
                } else {
                    print("Nope, sir")
                }
            }
            else if host == "www.apple.com" {
                if let headers = request.allHTTPHeaderFields {
                    print("Apple Headers: \(headers)")
                } else {
                    print("Nope, sir")
                }
            }
        }
        decisionHandler(.allow)
    }
}

我得到以下信息。

["User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8"] Headers: ["Accept-Language": "en-us", "Upgrade-Insecure-Requests": "1", "Accept-Encoding": "gzip, deflate, br", "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8"]