2

I am learning to write a BHO in c#, and i have written event handlers for DocumentComplete and BeforeNavigate2. During debugging i notice that they are triggered multiple times for certain webpages like yahoo.co.in.

I understand that this could be because of presence of multiple frames in the page. My questions are:-

  1. How do i know which is the event for the complete page being loaded?
  2. How do i know which is the event which gets triggered when we are about to navigate away from the page?

Adding Some Sample Code

private InternetExplorer iExplorer;
int IObjectWithSite.SetSite(object pUnkSite)
{
    if (pUnkSite != null)
    {
        ieInstance = (InternetExplorer)pUnkSite;
        // Register the DocumentComplete event.
        ieInstance.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(ieInstance_DocumentComplete);
        ieInstance.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(ieInstance_BeforeNavigate2);
    }
    return 0;
}

private void ieInstance_BeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
{
}

private void ieInstance_DocumentComplete(object pDisp, ref object URL)
{
}
Ashish Kumar Shah
  • 512
  • 1
  • 9
  • 26
  • 1
    1 (and maybe 2) sounds like it's answered by this: http://stackoverflow.com/a/8359461/593627 – George Duckett Feb 12 '14 at 10:54
  • @GeorgeDuckett, the part of it about `_pUnkSite` is wrong. The site object doesn't refer to the top browser object. – noseratio Feb 12 '14 at 11:07
  • 1
    @Noseratio: Ok, thanks for the correction. To be honest I am not familiar with the subject, I just found the answer (that was accepted) and assumed it was correct (without looking at the comments). – George Duckett Feb 12 '14 at 11:14
  • Yes, DocumentComplete fires for every frame in the web page. Which is why it has a URL argument, you can use that and compare it with the URL that you originally navigated, that one will be last. Counting off the frames is another way. Check [this answer](http://stackoverflow.com/a/3239313/17034). – Hans Passant Feb 12 '14 at 11:52

1 Answers1

2

Use the pDisp parameter of the BeforeNavigate2 and DocumentComplete event handlers, it refers to the instance of the SHDocVw.WebBrowser object corresponding to the frame (or the top browser):

static bool IsTop(object pDisp)
{
    var thisBrowser = pDisp as SHDocVw.WebBrowser;
    var parent = thisBrowser .Parent as SHDocVw.WebBrowser;
    return (parent == thisBrowser || parent == null);
}
noseratio
  • 59,932
  • 34
  • 208
  • 486