2015-06-21 82 views
0

有没有办法找出UIWebView内的内容何时更改标题?找出UIWebView标题何时更改?

例子:

我有一个UIWebView,并对其内容的变化,而经常通过JavaScript,所以我不能依靠webViewDidFinishLoading方法。标题更改时是否有方法可以调用特定的选择器或函数?

更新:这是我目前的做法,它的工作原理,但似乎并没有为最优:

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

回答

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; 
} 

之后,你需要在你的web视图上调用它。它为您的文档的title属性创建一个更新侦听器。

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

UPDATE

[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 });"]; 
+0

,我认为这是唯一的清洁方式。 – Ryan

+0

document.onpropertychange函数似乎不会在iOS浏览器上调用。你有解决方法吗? –

+0

我已更新一个新脚本。尝试这个。 –