5

I'm trying lots of things, posted many questions here, but I still can't manage to get the minimum size needed to hold an HTML page in a Cocoa WebKit WebView.
I made a weird manipulation of the DOM where I can get an approximation of the size of the HTML contents, as you can see in the picture, I resize the window based on this, and almost works, but what I realize is this:
If the Webview is intelligent enough to show accurate scroll bars (of course it is) so how come there's no interface so the programmer can get that value? is there a way that you know of?

PS: please don't provide javascript solutions, I need to implement this from the application. Anyway an html API as Webkit should be more savvy about its content than the hosted javascript code, shouldn't it?

enter image description here

Petruza
  • 11,744
  • 25
  • 84
  • 136

2 Answers2

0

While the solution by Alec Gorge worked for me, when placing the code into the webViewDidFinishLoad delegate method, I found that at least in iOS (and probably in OSX's Webkit as well) I could get the height of the web view just as well using this code:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    int h = webView.scrollView.contentSize.height;
    self.myWebViewHeightConstraint.constant = h;
}
Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149
0

You need to use Javascript to get the proper height.

Adapted from: How to get height of entire document with JavaScript?

(function () {
    var body = document.body,
        html = document.documentElement;

    return Math.max( body.scrollHeight, body.offsetHeight, 
                        html.clientHeight, html.scrollHeight, html.offsetHeight );
})();

This Javascript will give you the height of the HTML. You can inject it into the WebView like this:

NSString *height = [webView stringByEvaluatingJavaScriptFromString:@"(function(){var a=document.body,b=document.documentElement;return Math.max(a.scrollHeight,a.offsetHeight,b.clientHeight,b.scrollHeight,b.offsetHeight)})();"];

height now contains the height of the HTML as a string.

Community
  • 1
  • 1
Alec Gorge
  • 17,110
  • 10
  • 59
  • 71
  • Thanks, but I already tried this and doesn't work. body and html don't return any size. I can access this from the application via the DOM, but again body.scrollHeight and the other just don't have any values. Anyway, my application runs user-supplied htmls son I can't require any javascript code, I need to manage it from the application side. – Petruza Sep 05 '11 at 16:20
  • Correction, both body and html return the client size, which is the size of the window I set from the application, not the size of the html content. – Petruza Sep 05 '11 at 16:23
  • Are you running it in your `- (void)webViewDidFinishLoad:(WebView *)theWebView;` delegate method? – Alec Gorge Sep 05 '11 at 16:25