【问题标题】:Find out when UIWebView title changes?找出 UIWebView 标题何时更改?
【发布时间】:2015-06-21 22:42:16
【问题描述】:

有没有办法查明UIWebView 中的内容何时更改标题?

例子:

我有一个 UIWebView,它的内容通过 JavaScript 变化相当频繁,所以我不能依赖 webViewDidFinishLoading 方法。有没有办法在标题更改时调用特定的选择器或函数?

更新:这是我目前的方法,它有效,但似乎不是最佳的:

if(syncTitle){
    var updatePageTitleTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("syncPageTitle"), userInfo: nil, repeats: true);
}

【问题讨论】:

  • 如果你现在改用WKWebView,你可以在KVO中使用title属性。

标签: ios objective-c swift uiwebview


【解决方案1】:

我无法测试下面的代码,但它应该可以工作

首先你需要能够监听来自 js 的回调:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
     if([[[request URL] scheme] isEqualToString:@"titlechange"])
     {
       //Title was changed...
       return NO; //make sure the window location is not actually changed..
     }
     return YES;
}

之后,您需要在 webview 上调用它。它为您的文档的标题属性创建一个更新侦听器。

[YOUR_WEBVIEW stringByEvaluatingJavaScriptFromString:@"document.onpropertychange = function() {if (window.event.propertyName == 'title') {window.location = 'titlechanged://tralala';}};"];

更新

[YOUR_WEBVIEW stringByEvaluatingJavaScriptFromString:@"var target = document.querySelector('head > title');var observer = new window.WebKitMutationObserver(function(mutations) {mutations.forEach(function(mutation) {        window.location = 'titlechanged://tralala';});});observer.observe(target, { subtree: true, characterData: true, childList: true });"];

【讨论】:

  • 我认为这是唯一干净的方法。
  • 在 iOS 浏览器上似乎没有调用 document.onpropertychange 函数。你有解决方法吗?
  • 不幸的是,这似乎会导致服务器错误。您认为 Safari 是如何告知页面标题何时发生变化的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
相关资源
最近更新 更多