swift - 如何检测 WKWebView 中的哈希变化?

标签 swift macos hash wkwebview

我有一个使用 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/#page1http://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/

相关文章:

java - Apple AWT 内部异常 : NSWindow drag regions should only be invalidated on the Main Thread

java - 如何从 1 个公钥生成多个比特币地址?

ios - 从 swift 在 objective-c 中调用带有回调的函数

ios - 如何使用 Geofire 和 Firebase 对结果进行分页

swift - 带有僵尸的扩展 UIButton 测试在 super.init 中停止(编码器 : aDecoder)

macos - Mac 操作系统上的 Intellij IDEA : open file at a line number from terminal

c++ - 无法在 mac 上使用 qt app 打开文件

c - 设计通用哈希

ruby-on-rails - 如何对散列数组进行分组并在关键字后创建嵌套数组?

arrays - 如何使用数组中的多个 NSButton 执行功能?