Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser DocumentCompleted event fired more than once

Tags:

c#

.net

I've been researching this stuff and everyone seems to agree that the solution is to check the ReadyState of the Web Browser until is set to Complete.

But actually the event is sometimes fired with the ReadyState set to Complete several times.

I don't think there is a solution with that crappy .NET WebBrowser, but there might be one if I use the underlying DOM component.

Only problem is, I have no idea how do access the DOM component behind the WebBrowser that fires the DocumentCompleted event.

like image 249
Juan Avatar asked Jul 13 '10 16:07

Juan


1 Answers

DocumentCompleted will fire for each frame in the web page. The hard way is to count off the frames, shows you how to access the DOM:

private int mFrameCount;

private void startNavigate(string url) {
  mFrameCount = 0;
  webBrowser1.Navigate(url);
}

private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
  mFrameCount += 1;
  bool done = true;
  if (webBrowser1.Document != null) {
    HtmlWindow win = webBrowser1.Document.Window;
    if (win.Frames.Count > mFrameCount && win.Frames.Count > 0) done = false;
  }
  if (done) {
    Console.WriteLine("Now it is really done");
  }
}

The easy way is to check the URL that completed loading:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (e.Url.Equals(webBrowser1.Url)) {
        Console.WriteLine("Now it is really done");
    }
}
like image 144
Hans Passant Avatar answered Oct 20 '22 22:10

Hans Passant