如何正确监听 UIWebView 上的导航变化?

How to correctly listen to navigation changes on UIWebView?

我注意到 [UIWebViewDelegate webView:shouldStartLoadWithRequest:navigationType:] 仅通过传统的 <a href="..."> 链接调用,而不是单页网络应用程序 JavaScript 导航。

例如,如果我在 UIWebView 中转到 m.facebook.com 并开始点击顶部导航(请参见下面的屏幕截图),它永远不会触发该委托方法。

我想要挂钩方法的原因是因为我想在 UIWebView 上方添加后退和前进按钮,但我需要知道何时 enable/disable 这些按钮。我应该使用其他一些委托方法来正确收听导航更改吗?

更新:我还应该注意到,移动版 Safari 会正确更新 Facebook 移动网站上的 back/forward 按钮状态,因此我希望 Apple 也能为开发人员提供一种方法来执行此操作。

UIWebViewDelegate 和 WKNavigationDelegate(我刚刚在 facebook 上测试过)似乎都不支持。 this answer:

中列出了一些选项
  1. javascript injection to capture the page changes (read up on history.pushState).
  2. KVO to watch for changes to the webview (like the scrollview resizing)
  3. watching for the title change, as above.
  4. checking for updates every time the user taps the view.

更新

我还在 facebook 上尝试了 this answer,这涉及在每个新页面加载期间注入 javascript 以捕获 XMLHTTPRequests。它 有点 可以满足您的要求,但有点 hack。某些 Facebook 选项卡无法通过非常简单的实现正常工作,但您可以解决这些问题。