浏览SPA (single-page-application)网站时,我想获取UIWebView
的当前位置。
(是,我有意使用UIWebView
而不是WKWebView
。)
我知道有multiple approaches可以获取当前网址,例如:
webView.request?.url?.absoluteString
webView.request?.mainDocumentURL?.absoluteString
webView.stringByEvaluatingJavaScript(from: "window.location")
但是,对于SPA网站而言,对于上述每种方法,即使我导航到该SPA网站上的另一个页面,我仍会获得初始网址。
我该怎么办?
答案 0 :(得分:1)
第1步:创建自定义URL协议以捕获数据请求
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步:注册自定义URL协议
在将SPA加载到UIWebview之前,注册您的自定义URL协议。
URLProtocol.registerClass(CustomURLProtocol.self)
希望这会有所帮助!抱歉耽搁了,上班了。