iOS10 WKWebview - evaluateJavaScript( "document.height" ) 返回 nil



在我的应用程序中,我需要在WKWebView中获得网页的高度。所以我使用下面的代码:

webView.evaluateJavaScript(("document.height"), completionHandler: { contentHeight,error in
    print(contentHeight)
})

直到iOS 9,这返回正确的网页高度。但在iOS 10中,contentHeight总是nil

我设置

webView.scrollView.scrollEnabled = false

, web视图为UITableViewCell

webViewUITableViewCell的高度是可变的。网页视图有一个顶部和底部的约束,以适应单元格。

当我得到网页的高度,我希望它反映在单元格的高度

try this:

let javascriptString = "" +
            "var body = document.body;" +
            "var html = document.documentElement;" +
            "Math.max(" +
            "   body.scrollHeight," +
            "   body.offsetHeight," +
            "   html.clientHeight," +
            "   html.offsetHeight" +
        ");"
    webView.evaluateJavaScript(javascriptString) { (result, error) in
        if error == nil {
            if let result = result, let height = JSON(result).int {
                self.htmlContentHeight = CGFloat(height)
                self.resetContentCell()
            }
        }
    }

p。web渲染问题:iOS 10中WKWebView无法正确呈现

您可以尝试使用

webView.evaluateJavaScript(("document.body.offsetHeight"), completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    NSLog(@">>>%@",result);
})

最新更新