Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS10 WKWebview - evaluateJavaScript("document.height") return nil

In my app, I need to get the height of a webpage in a WKWebView. So I use the code below.

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

Until iOS 9, this returns the webpage height correctly. But in iOS 10, contentHeight is always nil.

I've set

webView.scrollView.scrollEnabled = false

and the web view is in a UITableViewCell.

The height of webView and of the UITableViewCell are variable. There's a top and bottom constraint on the web view to fit to the cell.

When I get the webpage height, I want it to be reflected in the cell's height.

like image 281
nicoJN Avatar asked Feb 07 '23 03:02

nicoJN


1 Answers

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()
            }
        }
    }

PS. WKWebiew rendering problem: WKWebView not rendering correctly in iOS 10

like image 179
orazz Avatar answered Feb 13 '23 05:02

orazz