Microsoft KB Archive/185127

= How To Call a Script Function from a VC WebBrowser Application =

Article ID: 185127

Article Last Modified on 6/29/2004

-

APPLIES TO


 * Microsoft Internet Explorer 4.0 128-Bit Edition
 * Microsoft Internet Explorer 4.01 Service Pack 2

-



This article was previously published under Q185127



SUMMARY
When hosting the WebBrowser control in a Visual C++ application, you may wish to execute a script function that exists on a Web page. This article demonstrates how to do this.



MORE INFORMATION
In order to call a script function that exists on a Web page, you have to use automation; in other words, IDispatch. Use the following steps to invoke a script function that exists on a Web page from your Visual C++ application:
 * 1) Get the IDispatch of the HTML document.
 * 2) Call IDispatch::GetIDsOfNames to get the ID of the script function.
 * 3) Call IDispatch::Invoke to execute the function.

The following Visual C++ source code demonstrates how to implement this in your own application. This code uses smart pointers created by the #import statement. You must include this #import statement in one of your source code files, preferably Stdafx.h:


 * 1) import "C:\winnt\system32\mshtml.tlb" // location of mshtml.tlb

void CMyClass::ExecuteScriptFunction {     // m_WebBrowser is an instance of IWebBrowser2 MSHTML::IHTMLDocument2Ptr spDoc(m_WebBrowser.GetDocument);

if (spDoc) {        IDispatchPtr spDisp(spDoc->GetScript); if (spDisp) {           // Evaluate is the name of the script function. OLECHAR FAR* szMember = L"evaluate"; DISPID dispid;

HRESULT hr = spDisp->GetIDsOfNames(IID_NULL, &szMember, 1,                                          LOCALE_SYSTEM_DEFAULT, &dispid);

if (SUCCEEDED(hr)) {              COleVariant vtResult; static BYTE parms[] = VTS_BSTR;

COleDispatchDriver dispDriver(spDisp, FALSE);

dispDriver.InvokeHelper(dispid, DISPATCH_METHOD, VT_VARIANT,                                      (void*)&vtResult, parms,                                       "5+Math.sin(9)"); }        }      }   }

The following is the HTML for the Web page that contains the evaluate function:

  Evaluate

 function evaluate(x) {        alert("hello") return eval(x) }   

  

