【问题标题】:How to detect hash changes in WKWebView?如何检测 WKWebView 中的哈希变化?
【发布时间】:2017-08-23 16:57:18
【问题描述】:

我有一个使用 javascript 的网站,该网站使用 angular 来控制您在网站上看到的内容。因此,http://somewebsite.com/#page1 会显示出来,当您单击选项卡时,位置会更改为 http://somewebsite.com/#page2。网站上不会有实际的重新加载,因此func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) 不会被触发。如何捕捉这些哈希变化?

显然 Apple 可以,因为 Safari 网络浏览器能够在地址栏中显示这些更改。


19.33 更新:

我做了一些研究。在 Safari 浏览器中使用 window.onhashchange 这将被触发,但在 WKWebView 中则不会。深入研究,我使用以下 javascript 每秒返回文档位置 href。

window.setInterval(function(){ alert(document.location) }, 1000);

在 WKWebView 中读取该警报时,它永远不会显示位置更改,而在 Safari 中您会看到 http://somewebsite.com/#page1http://somewebsite.com/#page2。好像 WKWebView 不支持这个非常烦人的功能。

【问题讨论】:

  • 你得到解决方案了吗?`我也面临同样的问题

标签: swift macos hash wkwebview


【解决方案1】:

无需注入任何 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
  }
}

不要忘记在deinit 中阻止webView.removeObserver(self, forKeyPath: "URL")

【讨论】:

  • 很好的答案!谢谢——这应该是公认的答案。
【解决方案2】:
let script = WKUserScript(source: "(function() { \"use strict\"; addEventListener(\"hashchange\", function(event) { webkit.messageHandlers.hashchangeMessageHandler.postMessage(null); }); }) ();", injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)

let configuration = WKWebViewConfiguration()
configuration.userContentController.add(self, name: "hashchangeMessageHandler")
configuration.userContentController.addUserScript(script)

self.webView = WKWebView(frame: CGRect.zero, configuration: configuration)

现在您可以使用以下方法获取哈希更改的 URL:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("Received message: \(message.name): \(message.body)")
    print(self.webView.url)

}

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 2010-10-15
    • 1970-01-01
    • 2020-02-08
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多