So I have wrote a BHO that exposes a function that I call from Javascript. My target system is Windows 8 IE 10 but the behavior that I get is same on Windows 7,8 32 and 64 bit, IE 10, IE 11 - it doesnt matter, I concluded it`s not system related.
So BHO works fine if you open a page that has JavaScript that calls function from a BHO - it gets defined and everything is good. I have a simple local page to test it that calls BHO.method(), same page hosted online also works great.
But in the following cases it doesnt work - i get "error: *property_added* is undefined". 1) if you open the same test page with JS code in a new additional tab. (If in just a single tab - it works as I`ve described above). 2) if you open any other page in a first tab and then get redirected using link to (or just paste in the address bar the URL of the) same old test page - "error: *property_added* is undefined".
Now the interesting part - I add a property (let`s call it) *property_added* in DocumentComplete event. I put alerts there I can see that DocumentComplete and AddProperty fires and runs at all the right times, for every page, but in cases that I describe I get this error on 'dynamic window = browser.Document.parentWindow;' - Exception from HRESULT: 0x800A01B6. Please help?
Below is the code that I use in OnDocumentComplete - it`s pretty standard though.
void OnDocumentComplete(object pDisp, ref object URL)
{
try
{
SHDocVw.IWebBrowser2 explorer = pDisp as SHDocVw.IWebBrowser2;
if (explorer != null)
{
dynamic window = explorer.Document.parentWindow;
IExpando windowEx = (IExpando)window;
PropertyInfo property = windowEx.GetProperty("BHO",BindingFlags.IgnoreCase); //BindingFlags.Default);
if (property == null)
{
property = windowEx.AddProperty("BHO");
}
property.SetValue(windowEx, this, null);
window.execScript("alert();");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
int IObjectWithSite.SetSite(object site)
{
this.site = site;
if (site != null)
{
browser = (InternetExplorer)site;
((DWebBrowserEvents2_Event)browser).DocumentComplete +=
new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
}
return 0;
}
UPDATE: When I add the following string
window.execScript("alert('BHO is '+(typeof(BHO) == 'undefined' ? 'undefined' : 'defined'));");
in the OnDocumentComplete right after property.SetValue(windowEx, this, null);
- redirected page case starts working fine all of a sudden. If I remove this string - it doesn`t work. How in the world this makes a difference??