web浏览器DocumentCompleted触发的事件不止一次浏览器、事件、web、DocumentCompleted

2023-09-02 21:08:27 作者:白狼的爱

我一直在研究这个东西,似乎每个人都同意的解决方案是检查的的readyState Web浏览器,直到设置来完成。

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.

但实际上,该事件被解雇,有时与的readyState 设置为完成好几次。

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

我不认为这是与蹩脚的.NET web浏览器的解决方案,但可能有一个,如果我使用底层DOM的组成部分。

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.

唯一的问题是,我不知道该怎么办访问触发DocumentCompleted事件的web浏览器背后的DOM组成部分。

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

推荐答案

DocumentCompleted将火在网页上的每个框架。硬的方法是计算过的图像,展示了如何访问DOM:

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");
    }
}