Resizing WP7 WebBrowser Height to Fit Content

At some point you’re probably going to need to have the height of a WebBrowser on your Windows Phone app resize automatically to fit the content, so that the other content on the page can wrap nicely around it. Fortunately MS have provided all of the functionality you need to pull this off, albeit in a somewhat roundabout way.

Adding the browser

First of all put a WebBrowser in to your XAML file, or alternatively add it pragmatically. Make sure IsScriptEnabled is set to true, by default it’s false.

If you’re adding the browser in code, make sure the height is at least 1 pixel.

Hooking up events

You’ll need to hook up the ‘ScriptNotify’ event, use the following code in the event handler:

protected void WebBrowser_ScriptNotify(object sender, NotifyEventArgs e)
{
	WebBrowser thisBrowser = (WebBrowser)sender;
	int height = Convert.ToInt32(e.Value);
	double newHeight = height * 1.5;

	thisBrowser.Height = newHeight;
}

This gets the browser that fired the event (so feel free to re-use the event for multiple browsers), gets the height the browser thinks it needs to display the content. The height value is actually set by the JavaScript, so due to the built-in scaling of the content you’ll need to multiply it by 1.5. Finally the browser’s height is set to the correct value to fit the content.

Add a teaspoon of JavaScript

Lastly, you need to add some JavaScript to the HTML you pass into the browser:

<script type="text/javascript">
    window.onload = function () {
        var elem = document.getElementById('content');
        window.external.Notify(elem.scrollHeight + '');
    }
</script>

This code will find an element with the ID of ‘content’, and send the height to your program. This means you’ll need to wrap all of your content in a div like so:

<div id="content">
    <p>Hello World</p>
</div>

You may be wondering why we don’t just get the scrollHeight of body. While experimenting I found this was the most reliable – but if body works for you then it is the more elegant solution. You may also be wondering why we add ” to the scrollHeight in the JavaScript. This is due to window.external.Notify only supporting text strings, however the height is a number. By adding ” we convert the number to a string meaning window.external.Notify will work as intented. If you ever find Notify not working – check the datatype, it fails silently.

Finishing up

This should be enough for you to get started. You’ll probably want to customise the CSS to match the phone’s current theme, but that’s another guide for another day. One tweak you should probably think about doing now is to add some padding to the content div, otherwise the HTML you output tends to look out of place rammed right up against the border of the WebBrowser.

If you find the height returned isn’t correct, it’s most likely due to the scaling of the web content. Set the viewport width to a fixed value (you can pass in the width of the WebBrowser if generating the HTML on the fly, or you have the ability to process it before the browser reads in the HTML). You may also need to set the width of the div as well, using the aforementioned method.

Setting the viewport:

<meta name="viewport" content="width=320" />

Setting the div width + padding:

<style type="text/css">#content { padding: 10px; width: 300px; }</style>

1 comment

Hi Sir..

I have read your blog ‘http://dan.clarke.name/2011/05/resizing-wp7-webbrowser-height-to-fit-content’.

Thanks for the blog. This what I want to my project. I have follow some of your instructions for my project. Now I need a help from you. How to fit the HTML content to the web browser in Windows Phone 7?

I am trying to re-size the browser with the size of html content. I have try with following code.

private void WebBrowser_OnLoaded(object sender, RoutedEventArgs e)
{
String htmlHead = “{0}{1}”;
myWebView.NavigateToString(String.Format(htmlHead, getScript(), getHTMLContent()));
myWebView.IsScriptEnabled = true;
myWebView.ScriptNotify += new EventHandler(WebBrowser_ScriptNotify);
}

private void WebBrowser_ScriptNotify(object sender, NotifyEventArgs e)
{
if (!string.IsNullOrEmpty(e.Value) && !(e.Value == “”))
{
this.myWebView.Height = double.Parse(JsonParsing(e.Value));
myWebView.UpdateLayout();
}
}

private string getScript()
{
string script = “”;
script += “function ResizeWebBrowser()”;
script += “{“;
script += “var _renderedHeight=document.body.firstChild.offsetHeight * 0.66;”;
script += “var _json = ‘{\”rendered_height\” : ‘+_renderedHeight+’}’;”;
script += “window.external.notify(_json)”;
script += “}”;
script += “ResizeWebBrowser();”;
script += “”;
return script;
}

public string getHTMLContent()
{
StringBuilder htmlBody = new StringBuilder();
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
htmlBody.Append(“”);
return htmlBody.ToString();
}

It’s working fine . Now I can re size the browser. But now I am facing one problem.
That is, the content is exceed from the browser. If I double click the page, then only the the content become to fit to the browser.
Please let me any idea to fit the content to the browser.

This is my email id:

vijaydhascr@gmail.com
vijaydhascr@hotmail.com

Please help me to resolve this problem.
Thanks and Regards
C. Vijayadhas

Leave a Reply to Vijaydhas Cancel reply