在使用WKWebView时,通过如下方法获取到的网页高度与实际高度不符合,出现一大段空白:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题,动态改变
self.title = webView.title;
__block CGFloat webViewHeight;
//获取内容实际高度(像素)@"document.getElementById(\"content\").offsetHeight;"
[webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
// 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度,看参考资料说是对于加载html字符串的情况下使用后者可以(@"document.getElementById(\"content\").offsetHeight;"),但如果是和我一样直接加载原站内容使用前者更合适
//获取页面高度,并重置webview的frame
webViewHeight = [result doubleValue];
NSLog(@"web内容高度%f",webViewHeight); // 远高于实际值
}];
}
解决方案,初始化WKWebView时注入JS代码配置configuration
//注入JS以缩放网页,避免获取到的网页高度远超实际高度,出现超长空白页面
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
// 初始化WKWebView注意带上configuration
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.webViewContent.frame.size.width, self.webViewContent.frame.size.height) configuration:wkWebConfig];