UIWebView时获取网页标题是在网页加载成功后执行"document.title"js代码来获取标题,WKWebView当然也可以通过此方法获取,但有时在加载成功后H5业务修改标题则不能实时获取新的标题
解决方案如下:
//添加监听
[self.wkwebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
// 根据监听 实时修改title
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *,id> *)change
context:(void *)context
{
if ([keyPath isEqualToString:@"title"]) {
if (object == self.webView)
{
self.title = self.webView.title;
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
}
//移除监听
- (void)dealloc{
[webView removeObserver:self forKeyPath:@"title" context:nil];
}