How to tell when a WebBrowser has fully loaded, the final answer

Quite often I see in forums people asking how to tell when a hosted WebBrowser control has finished loading. What follows are any of a half a dozen solutions, but often they are either out dated or just don’t work. After fighting with this one again in a project of mine, I have decided to post a solution that DOES work, in VB.NET or C#, VS2005 and VS2008.

If you’ve ever placed code in the DocumentCompleted event, you’ve undoubtedly noticed that it fires multiple times and off the shelf is of little use to determining when the page has actually completed. I’ve seen suggestions ranging from using timers to very complex event sink something or other, most of which don’t quite work. This is one of those things that I cannot imagine how it has not made the documentation.

The solution itself is pretty simple, and also works when the page contains frames, which is a whole other set of forum listings. The key is in the event arguments. In the DocumentCompleted event, e.Url.AbsolutePath contains the URL of the document that has completed. In the case of a page with frames, or one that fetches other pages, those paths will be in the AbsolutePath variable. When the page has truly finished, this will equal the corresponding value of the WebBrowser control. The whole thing looks like this.

C#

void BrowserDocumentCompleted(object sender,
        WebBrowserDocumentCompletedEventArgs e)
{
  if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
    return; 

  //The page is finished loading 
}

VB.NET

Private Sub BrowserDocumentCompleted(ByVal sender As
            Object,  ByVal e As WebBrowserDocumentCompletedEventArgs)
  If e.Url.AbsolutePath <> TryCast(sender, WebBrowser).Url.AbsolutePath 
   Then
    Return
  End If
  'The page is finished loading 
End Sub 

That’s all it takes. Note that the VB.NET code was created with a code translator and has not been tested.

Cheers.

6 Responses to “How to tell when a WebBrowser has fully loaded, the final answer”

  1. Thanks a lot mate – looked at 100 different solutions, but this worked…

    Thumps up!!!

  2. Glad to help :)

  3. Well done! I've been looking around for this for some time!

  4. Thank you so much!!! I have been searching high and low and yours is the only one that worked.

  5. Glad I could help :) this one was a pain to get right!

  6. sorry but it doesn't work
    it just tell you when the document is loaded not when ajax is loaded for example

Leave a Reply

Captcha
Enter the letters you see above.