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

时间:2011-12-02 16:23:40

标签: c# .net com browser bho

为什么在加载页面之前会触发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;
    }
}

1 个答案:

答案 0 :(得分:3)

因为页面上还有其他文档。例如,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
}

_pUnkSite是从SetSite传入的网站。