有没有办法找出UIWebView
内的内容何时更改标题?
示例:
我有一个UIWebView,其内容经常通过JavaScript更改,因此我不能依赖webViewDidFinishLoading
方法。有没有办法在标题改变时调用特定的选择器或函数?
更新:这是我目前的方法,它有效,但似乎不是最佳的:
if(syncTitle){
var updatePageTitleTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("syncPageTitle"), userInfo: nil, repeats: true);
}
答案 0 :(得分:2)
我无法测试下面的代码,但它应该可以运行
首先,您需要能够侦听来自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;
}
之后你需要在你的网页浏览中调用它。它为文档的title属性创建更新侦听器。
[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 });"];