5

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
nicoJN
  • 61
  • 1
  • 6
  • I'm facing this problem as well, my current workaround is to use its contentSize.height, for now. – wint Sep 18 '16 at 03:20

2 Answers2

9

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

Community
  • 1
  • 1
orazz
  • 2,178
  • 2
  • 15
  • 16
  • Thank you for reply! I can get height of webpage! But if I set WKWebview.scrollView.scrollEnabled = false , I can't get height. Do you know some ideas? – nicoJN Sep 18 '16 at 09:45
  • I have the same problem. Maybe this will help you: http://stackoverflow.com/a/39556938 – orazz Sep 18 '16 at 12:00
0

You can try using

webView.evaluateJavaScript(("document.body.offsetHeight"), completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    NSLog(@">>>%@",result);
})
K Scandrett
  • 16,390
  • 4
  • 40
  • 65