Why does DocumentComplete event of WebBrowser COM object fire before page is loaded? I thought that this event is only fired when page is fully rendered in browser's window.
this is my BHO implementation:
[ComVisible(true),
Guid("5a954357-44bd-4660-9570-17bb1b71eeaa"),
ClassInterface(ClassInterfaceType.None)]
public class BHO : IObjectWithSite
{
private WebBrowser browser;
private DateTime startTime;
private DateTime endTime;
private object _pUnkSite;
public void OnDocumentComplete(object pDisp, ref object URL)
{
if (!ReferenceEquals(pDisp, _pUnkSite))
{
return;
}
using (StreamWriter sw = File.AppendText("log_path"))
{
endTime = DateTime.Now;
TimeSpan ts = endTime.Subtract(startTime);
sw.WriteLine("completed in {0}.{1}", ts.Seconds, ts.Milliseconds);
}
}
public void OnBeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
{
if (!ReferenceEquals(pDisp, _pUnkSite))
{
return;
}
startTime = DateTime.Now;
}
public int SetSite(object site)
{
if (site != null)
{
_pUnkSite = site;
browser = (WebBrowser)site;
browser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
browser.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);
}
else
{
browser.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
browser.BeforeNavigate2 -= new DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);
browser = null;
}
return 0;
}
public int GetSite(ref Guid guid, out IntPtr ppvSite)
{
IntPtr punk = Marshal.GetIUnknownForObject(browser);
int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
Marshal.Release(punk);
return hr;
}
}
Because there are other documents on a page. An iframe, or an image, for example, will fire the DocumentComplete
event. What you need to do is ensure that the object that raised DocumentComplete
is the actual page. For example:
private void _webBrowser2Events_DocumentComplete(object pdisp, ref object url)
{
if (!ReferenceEquals(pdisp, _pUnkSite))
{
//Exit, because the DocumentComplete is not the document complete for the page.
return;
}
//Do your normal stuff here
}
Where _pUnkSite
is the site that was passed in from SetSite
.
来源:https://stackoverflow.com/questions/8359379/documentcomplete-is-firing-before-page-is-fully-loaded