MSHTML Hosting – Calling JavaScript From Host

I don’t know how often someone would want to call a JavaScript (JS) function in the WebBrowser control from the host application. Since the host can control many, if not more, aspects of the HTML content externally using IDocHostUIHandler or the MSHTML DOM interfaces, it seems unnecessary to implement a method in JS and call that method from the host. But, if you need to for some reason, here’s how to do it:


IHTMLDocument* pHTMLDoc = /* however you can get the IHTMLDocument */

DISPID idMethod = 0;
OLECHAR FAR* sMethod = L"DoSomething";
IDispatch* pScript = 0;
pHTMLDoc->get_Script(&pScript);
HRESULT hr = pScript->GetIDsOfNames(IID_NULL, &sMethod, 1, LOCALE_SYSTEM_DEFAULT,
                                    &idSave);
if (SUCCEEDED(hr)) {
  // invoke assuming no method parameters
  DISPPARAMS dpNoArgs = {NULL, NULL, 0, 0};
  hr = pScript->Invoke(idSave, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD,
                       &dpNoArgs, NULL, NULL, NULL);
}
pScript->Release();
pHTMLDoc->Release();

Notice we are using the IHTMLDocument interface, not the more often used IHTMLDocument2 interface. Also note that I am assuming no arguments are passed to the JS method. Check out IDispatch::Invoke for more information on calling a method with arguments. CodeProject has a few nice articles as well.

2 Replies to “MSHTML Hosting – Calling JavaScript From Host”

  1. hi,
    this is what I am looking for, but can you translate this to c#? That would help me out a lot.

    Thanks
    Nuz

  2. IHTMLDocument doc1 = (IHTMLDocument)axWebBrowser1.Document ;
    HTMLWindow2 iHtmlWindow2 = (HTMLWindow2) doc1.Script ;
    iHtmlWindow2.execScript( “functionName(param1);” , “javascript” ) ;

Comments are closed.