如何检测WKWebView中的哈希变化? [英] How to detect hash changes in WKWebView?

查看:411
本文介绍了如何检测WKWebView中的哈希变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a website that uses javascript that uses angular to control what you see on the website. So http://somewebsite.com/#page1 is shown and when you click on a tab that location changes to http://somewebsite.com/#page2. There will be no actual reload on the website and therefor func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) will not get triggered. How can you catch these hash changes?

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

Clearly Apple can, since the Safari webbrowser is able to show these changes in the location bar.

更新19.33:

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

I did some research. Using window.onhashchange in the Safari browser this will get fired however in the WKWebView it does not. Diving deeper I use the following javascript to return the document location href every second.

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

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

When reading that alert in WKWebView it never shows that the location changes, while in Safari you see http://somewebsite.com/#page1 and http://somewebsite.com/#page2. It seems like WKWebView does not support this feature which is extremely annoying.

推荐答案

无需注入任何JS.我使用了webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil),它正在检测所有URL更改,包括哈希更改.然后:

No need to inject any JS. I used webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil) and this was detecting any URL changes, including hash changes. Then:

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").

这篇关于如何检测WKWebView中的哈希变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆