我有一个使用 javascript 的网站,该网站使用 angular 来控制您在网站上看到的内容。所以http://somewebsite.com/#page1显示,当您单击一个选项卡时,位置更改为 http://somewebsite.com/#page2 .网站上不会有实际的重新加载,因此 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
不会被触发。你怎么能捕捉到这些哈希变化?
显然 Apple 可以,因为 Safari 网络浏览器能够在地址栏中显示这些更改。
更新 19.33:
我做了一些研究。使用 window.onhashchange
在 Safari 浏览器中,这将被触发,但在 WKWebView 中则不会。深入研究我使用以下 javascript 每秒返回文档位置 href。
window.setInterval(function(){ alert(document.location) }, 1000);
在 WKWebView 中读取该警报时,它永远不会显示位置更改,而在 Safari 中您会看到 http://somewebsite.com/#page1和 http://somewebsite.com/#page2 .看起来 WKWebView 不支持这个非常烦人的功能。
最佳答案
无需注入(inject)任何 JS。我用了webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
这是检测任何 URL 更改,包括哈希更改。然后:
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
if object as AnyObject? === webView && keyPath == "URL" {
onURLChange(webView.url) // onURLChange does whatever you want
}
}
不要忘记
webView.removeObserver(self, forKeyPath: "URL")
在 deinit
虽然阻止。
关于swift - 如何检测 WKWebView 中的哈希变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45845457/