有没有办法发现 UIWebView
中的内容何时更改标题?
例子:
我有一个 UIWebView,它的内容通过 JavaScript 更改得相当频繁,所以我不能依赖 webViewDidFinishLoading
方法。有没有办法在标题更改时调用特定的选择器或函数?
更新:这是我目前的方法,它有效,但似乎不是最优的:
if(syncTitle){
var updatePageTitleTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("syncPageTitle"), userInfo: nil, repeats: true);
}
最佳答案
我无法测试下面的代码,但它应该可以工作
首先你需要能够监听来自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 - 找出 UIWebView 标题何时更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30970042/