[英]UIWebView get current URL of SPA (single page application) website
浏览SPA(单页应用程序)网站时,我想获取UIWebView
的当前位置。
(是的,我有意使用UIWebView
而不是WKWebView
。)
我知道有多种获取当前URL的方法,例如:
webView.request?.url?.absoluteString
webView.request?.mainDocumentURL?.absoluteString
webView.stringByEvaluatingJavaScript(from: "window.location")
但是,对于SPA网站,对于上述每种方法,即使我导航到该SPA网站上的另一个页面,我也会获得初始网址。
我能做什么?
步骤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
在将SPA加载到UIWebview之前,请注册自定义URLProtocol。
URLProtocol.registerClass(CustomURLProtocol.self)
希望这可以帮助! 抱歉耽搁了,上班了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.