UIWebView 获取 SPA(单页应用)网站的当前 URL

UIWebView get current URL of SPA (single page application) website

我想在浏览 SPA (single-page-application) 网站时获取我 UIWebView 的当前位置。
(是的,我有意使用 UIWebView 而不是 WKWebView。)

我知道有multiple approaches可以得到当前的URL,比如:

webView.request?.url?.absoluteString
webView.request?.mainDocumentURL?.absoluteString
webView.stringByEvaluatingJavaScript(from: "window.location")

但是,对于 SPA 网站,对于上述每种方法,即使我导航到该 SPA 网站上的另一个页面,我也会得到初始 url。

我能做什么?

第 1 步:创建自定义 URLProtocol 以捕获数据请求

class CustomURLProtocol: URLProtocol, URLSessionDataDelegate, URLSessionTaskDelegate {

    // If this returns false, the first request will basically stops at where it begins.
    override class func canInit(with request: URLRequest) -> Bool {
        return true
    }

    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }

    override func startLoading() {

        print(self.request.url) // URL of Data requests made by UIWebView before loading.  
        URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil).dataTask(with: self.request).resume()
    }

    override func stopLoading() {

    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {

        // Data request responses received.  
        self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed)
        completionHandler(.allow)
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {

        // Data request data received.
        self.client?.urlProtocol(self, didLoad: data)
        self.urlSession(session, task: dataTask, didCompleteWithError: nil)
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

        if let error = error {

            self.client?.urlProtocol(self, didFailWithError: error)
            return
        }

        print(self.request.url) // URL of Data requests completed.
        self.client?.urlProtocolDidFinishLoading(self)
    }
}

第 2 步:注册您的自定义 URLProtocol

在 UIWebview 中加载 SPA 之前注册您的自定义 URLProtocol。

URLProtocol.registerClass(CustomURLProtocol.self)

希望对您有所帮助!很抱歉耽误了工作。