Autosize WebView to its Content

Ever wanted to resize the WebView controller according to its HTML content for Windows or Windows Phone apps?

I had this same problem working on a project and solved it by determining the scroll height/width of the HTML content and setting the width of the WebView controller accordingly. I've wrapped all the necessary functionality into an extension method for easy re-use.

WebViewExtensions.cs

public static class WebViewExtensions  
{
    public static void ResizeToContent(this WebView webView)
    {
        var heightString = webView.InvokeScript("eval", new[] {"document.body.scrollHeight.toString()" });
        int height;
        if (int.TryParse(heightString, out height))
        {
            webView.Height = height;
        }

        var widthString = webView.InvokeScript("eval", new[] {"document.body.scrollWidth.toString()" });
        int width;
        if (int.TryParse(widthString, out width))
        {
            webView.Width = width;
        }        
    }
}

And here's how you can use it in your project:

XAML (e.g. Page.xaml)

<ScrollViewer>  
    <WebView x:Name="ContentInfo" Height="200" />
</ScrollViewer>  

Code-Behind (e.g. Page.xaml.cs)

// constructor
public Page()  
{
    ContentInfo.NavigationCompleted += (sender, args) => sender.ResizeToContent();
    ContentInfo.Navigate(new Uri("http://www.jasonpoon.ca"));
}