15 08 2009
Displaying custom HTML in WebBrowser control
I am using WebBrowser control to show preview of automatically generated HTML. Users can select options and preview pane reflects those changes automatically. WebBrowser control has some problems that have been here for years already. Here is my example about how to show custom HTML in WebBrowser control.
When we look at methods and properties of WebBrowser control our common sense tells us that something like this should work (VB.NET users: delete “;” after this line):
webBrowser1.DocumentText = "some text here";
And it works – only once. All subsequent assignments change nothing. When we try to refresh WebBrowser control we get only white are. Setting AllowNavigation propertyto true – some guys suggest it – has no effect also.
To get all assignments works after first one we need to navigate to some page. about:blank is good candidate because it “exists” also in local machine for sure. And that’s not enough – we need to write something to document. After that we can show our custom HTML.
private void DisplayHtml(string html)
if (webBrowser1.Document != null)
webBrowser1.DocumentText = html;
NB! You should set AllowNavigation property to true before you deal with contents shown to users.
Keeping users on generated page
Now we can show HTML correctly and everything seems to be okay. But are we finished? Answer is yes if we want users to be able to follow the links we show to them and no if we want to keep users on generated page.
Currently we allowed navigation because otherwise we cannot move to about:blank. We have to allow this navigation and disable all other navigation. Fortunately there isNavigating event of WebBrowser. In Navigating event we can do our filtering.
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
if (e.Url.ToString() != "about:blank")
e.Cancel = true;
So, that’s it. We can now display our custom HTML in WebBrowser control as many times as we want. If you have some better trick then please let me know!