Getting a WebView's total scroll size ( the size of the HTML content )
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 sc开发者_JAVA技巧roll 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?
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.
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;
}
精彩评论