获取 WKWebView 高度

1、这种方法只能在网页加载完成后调用一次,如果网页中有图片异步加载出来,则不会调用。

//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    
     
    //    document.body.scrollHeight(加载HTML源站用这个)   document.body.offsetHeight;(加载HTML字符串)
    [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id Result, NSError * error) {
    
    
        NSString *heightStr = [NSString stringWithFormat:@"%@",Result];
         
        CGFloat height = heightStr.floatValue+15.00; 
        //网页加载完成
        NSLog(@"加载网页高度:%f",height); 
    }];

    [webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
}

2、但是上面有一部分高度无论如何都不对, KVO 监听 ContentSize

	[self.webView.scrollView addObserver:self
                              forKeyPath:@"contentSize"
                                 options:NSKeyValueObservingOptionNew
                                 context:nil];


- (void)dealloc {
    
    
    [self.webView.scrollView removeObserver:self
                                 forKeyPath:@"contentSize"];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    
    UIScrollView * scrollView = object; 
    NSLog(@"高度%@", @(scrollView.contentSize.height));
}

此处只是记录,摘抄自WKWebView 获取高度

猜你喜欢

转载自blog.csdn.net/u014651417/article/details/122400481