DocumentComplete在页面完全加载之前触发

本文关键字:加载 DocumentComplete | 更新日期: 2023-09-27 18:16:24

为什么WebBrowser COM对象的DocumentComplete事件在页面加载之前触发?我认为这个事件只有在页面完全呈现在浏览器窗口时才会触发。

这是我的BHO实现:

[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;
    }
}

DocumentComplete在页面完全加载之前触发

因为页面上还有其他文档。例如,iframe或图像将触发DocumentComplete事件。您需要做的是确保引发DocumentComplete的对象是实际的页面。例如:

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
}

其中_pUnkSiteSetSite传入的位点