如何在iOS webview中检测资源请求,与Android的“shouldInterceptRequest”相同?

问题描述 投票:0回答:1

在 iOS WKWebView 中,有没有办法检测网站何时发出 资源请求(例如通过 Ajax 的 HttpRequest)?

Android中,有一个非常方便的方法“shouldInterceptRequest”,但我在iOS中找不到等效的方法。

ios swift webview xmlhttprequest wkwebview
1个回答
0
投票

您可以使用

WKWebView
检查来自
WKNavigationDelegate
的请求。
您可以覆盖
webView:decidePolicyFor:...
来检查请求,检查其类型(例如单击的链接、提交的表单等)并检查关联的
URL
以采取某些操作:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView(frame: view.bounds)
        webView.navigationDelegate = self
        view.addSubview(webView)
        let url = URL(string: "https://www.google.com")!
        let request = URLRequest(url: url)
        webView.load(request)
    }

    // WKNavigationDelegate method to intercept resource requests
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        // `navigationType` indicates how this request got created
        // `.other` may indicate an Ajax request
        // More info: https://developer.apple.com/documentation/webkit/wknavigationtype

        // Update: remove the if clause for now and see if you get any result for your Ajax requests.
        // if navigationAction.navigationType == .other {
            if let request = navigationAction.request.url {
                print("Resource Request: \(request)")
            }
        // }

        // Allow the navigation to continue or not, depending on your business logic
        decisionHandler(.allow)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.