Yesterday I had to fix a bug that had been discovered at our form that used the WebBrowser control. Here is the description of the problem and solution. I hope it will save you the time I've spent on this.
The problem
When you use the WebBrowser.DocumentText in order to set the HTML of the document, some links don't work when you click on them.
For example, the following link to the user's desktop doesn't work: <a href="file:///C:/Documents%20and%20Settings/user/Desktop/jon.png">File</a>. This happens because of permissions problem I guess - a web browser tries to execute a file on the user's desktop...
The solution
After trying various solutions, only this one proved to really work.
Before you set the DocumentText property, register to the DocumentCompleted event:
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.DocumentText = textBox1.Text;
Now, on the event handler we will register to the links Click event (you can't do that right after you set the DocumentText property because the Document property might not be complete by then):
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
foreach (HtmlElement link in webBrowser1.Document.Links)
{
link.Click += new HtmlElementEventHandler(link_Click);
}
}
What we have left is to take care of link clicks. What I do here is quite simple - I retrieve the href attribute and execute it using the Process.Start method. This will jump above the security barriers and open the file with the default program associated with it. Right after that I prevent the event to continue bubble through the layers:
void link_Click(object sender, HtmlElementEventArgs e)
{
// Get the file path
string file = (sender as HtmlElement).GetAttribute("href");
// Execute it
Process.Start(file);
// Prevent the event bubbling
e.BubbleEvent = false;
e.ReturnValue = false;
}
That's it!
Pay attention that if you have some other links in the HTML document, you should filter them somewhere and let the WebBrowser control to take care of them.
Hope it helps,
Shay.