2

I need the correct page height of a WebBrowser control.

In Javascript, this works:

var body = document.body;
var html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );

Duplicate questions exist on SO, with the the following methods suggested:

webBrowser.Document.Body.ScrollRectangle.Height;     
webBrowser.Document.GetElementsByTagName("body")[0].OffsetRectangle.Bottom;
webBrowser.Document.GetElementsByTagName("body")[0].OffsetRectangle.Height;

Except none return the same value as the JS code.

I'm open to the possibility that the JS value is wrong but I am fairly confident it is correct because scrolling to the bottom of the page and adding the ScrollTop position to the control height produces the same value.

webBrowser1.Document.GetElementsByTagName("HTML")[0].ScrollTop + webBrowser1.Height; 

For my particular case, C# is returning a height of 510, while JS returns correct height, 529. This inconsistency is throwing off a custom scroll bar I have written.

livin_amuk
  • 1,285
  • 12
  • 26
  • 1
    Do you have access to change the page you're talking about? If so you could put that Javascript in your page, invoke it from the Webbrowser and grab the result. There's a thread with an example [HERE](http://stackoverflow.com/questions/1437251/calling-a-javascript-function-in-the-c-sharp-webbrowser-control) – Equalsk Dec 15 '15 at 11:37
  • That is working for me, thank you, but I'll leave the question open in hopes of a more direct solution. – livin_amuk Dec 15 '15 at 11:50
  • No problem! I'll move it to an answer anyway for everyone's benefit and if I think of anything else I'll update it. – Equalsk Dec 15 '15 at 11:59

1 Answers1

3

If you have access to the code for the page then you can add the Javascript in your question to that page and then invoke it from the Webbrowser and retrieve the result.

HTML

<html>
<head>
<script>
function GetPageHeight()
{
    var body = document.body;
    var html = document.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;
}
</script>
</head>
<body>
Test
</body>
</html>

C#

int height = (int)webBrowser1.Document.InvokeScript("GetPageHeight");
livin_amuk
  • 1,285
  • 12
  • 26
Equalsk
  • 7,954
  • 2
  • 41
  • 67