IHTMLDOMNode::appendChid() won't always work as expected

159 views Asked by At

I am writing a BHO in C++ which involves basically two stages.

Stage 1: Open new window from BHO and navigate it to a website URL (from the BHO), inject some Javascript code into its document once the DISPID_DOCUMENTCOMPLETE event fires for the appropriate URL, then invoke some code from js. The js engine will then crunch some more code and finally point its window at some other URL by means of window.location.href.

Stage 2: Once DISPID_DOCUMENTCOMPLETE fires inside the BHO for the new URL the flow goes the same route: Inject script, etc. This is where I get into trouble.

  1. Happens on Win 7 32 bits + IE11, does not happen on Win XP 32bits + IE8
  2. Issue is with stage 2 - injection fails. I have tried to appendChild on both first body tag and first head tag with the same result.
  3. There are tests for all HRESULT return values involved and also for validity of interface pointers returned and they all pass
  4. But when time comes to invoke a function from the script, GetIDsOfNames() returns a hresult of -2147352570 (Unknown name) when passing the name of my function from the javascript code.
  5. Inspecting the DOM in IE reveals the js code was not injected
  6. This always happens when IE is launched and then no more mouse clicks or keyboard events occur. It happens, however, only in about 5% or less of the cases where IE is launched and a click occurs (anywhere - desktop, title bar, client area of any window).

Attempts to fix this: Used SendInput() in order to simulate mouse click. Works as described above at point 6. Used a timer fired on that second URL DISPID_DOCUMENTCOMPLETE event and went on with injection after some seconds - that crashes the browser when IHTMLDocument2::createElement() gets called.

Any reasons to this strange behaviour and perhaps a way to fix it ? Thanks!

1

There are 1 answers

0
kellogs On

Looks like I had to renew the IWebbrowser2 instance - it changes upon page navigation. Fetch the new interface pointer by querying the second parameter sent along with the DISPID_DOCUMENTCOMPLETE event.

Link to it: https://msdn.microsoft.com/en-us/library/aa768282%28v=vs.85%29.aspx