With the advent of IE11, IHTMLWindow2::execScript()
is deprecated. The recommended approach is to use eval()
instead. I'm automating IE via its C++ COM interfaces, and I have been unable to find how to accomplish this. Can someone point me to the example I've obviously missed in my searching? If it's not possible to execute code via eval
, what's the appropriate way to inject JavaScript code into a running instance of Internet Explorer now that execScript
is no longer available?
EDIT: Any solution that will work for the project I'm working on must work out-of-process. I am not using a Browser Helper Object (BHO), or any type of IE plugin. Thus, any solution that involves an interface that cannot be properly marshaled cross-process won't work for me.
I have now verified the
eval
approach works consistently with IE9, IE10 and IE11 (error checks skipped for breavity):Feels even better than
execScript
, because it actually returns theresult
. It works also in C# with WinForms'WebBrowser
:That said,
execScript
still works for IE11 Preview:And it still discards the
result
, as it always did.A bit off-topic, but you don't have to stick with
eval
for this. This approach allows to execute any named method available inside the namespace of the JavaScriptwindow
object of the loaded page (via IDispatch interface). You may call your own function and pass a live COM object into it, rather than a string parameter, e.g.:I'd prefer the above direct call to
eval
where possible.[EDITED]
It takes some tweaks to make this approach work for out-of-process calls. As @JimEvans pointed out in the comments,
Invoke
was returning error 0x80020006 ("Unknown name"). However, a test HTA app worked just fine, what made me think to try IDispatchEx::GetDispId for name resolution. That indeed worked (error checks skipped):The full C++ test app is here: http://pastebin.com/ccZr0cG2
[UPDATE]
This update creates
__execScript
method on awindow
object of a childiframe
, out-of-proc. The code to be injected was optimized to return the targetwindow
object for later use (no need to make a series of out-of-proc calls to obtain theiframe
object, it's done in the context of the main window):Below is the code for C++ console app (pastebin), some error checks skipped for breavity. There's also a corresponding prototype in .HTA, which is more readable.