Click here to Skip to main content
13,552,729 members
Click here to Skip to main content
Add your own
alternative version


219 bookmarked
Posted 28 May 2002
Licenced CPOL

JavaScript call from C++

, 7 Jul 2011
Rate this:
Please Sign up or sign in to vote.
A class for easy implementation of JavaScript calls from C++ code.

Sample Image


Sometimes when you are using the IE Browser Control inside of a C++ application, you need to get access to the HTML elements. We can do it by using standard COM objects like IWebBrowser2, IHTMLDocument2, etc. By this method, we can easily implement features like click button, click anchor, get input string, get HTML text, etc. Unfortunately, Microsoft did not provide similar objects for JavaScript. At any case, to make control for a JavaScript object inside of an HTML page is possible by using the traditional COM approach. This article describes the class CWebPage which allows to do it and a technique to call a JavaScript function from C++ code.

How to do

As a result of using the presented class, it will be easy to call any JavaScript function from C++ code. For implementing this feature, we should get a pointer to the IHTMLDocument2 interface. If we are using the CHtmlView class from MFC, we can get one by using the member function CHtmlView::GetHtmlDocument(). In the case of using IWebBrowser or IWebBrowser2 components, the function get_Document will bring us the desired interface. Here is an example:

CComPtr<IDispatch> spDisp = CHtmlView::GetHtmlDocument();

The rest of the things will be done by the CWebPage class. Here is an example of a JavaScript call without parameters:


An example of a JavaScript call with two parameters will looks like:


The class implementation

class CWebPage
  virtual ~CWebPage();

  bool SetDocument(IDispatch* pDisp);
  LPDISPATCH GetHtmlDocument() const;
  const CString GetLastError() const;
  bool GetJScript(CComPtr<IDispatch>& spDisp);
  bool GetJScripts(CComPtr<IHTMLElementCollection>& spColl);
  CString ScanJScript(CString& strAText,CStringArray& args);

  bool CallJScript(const CString strFunc);
  bool CallJScript(const CString strFunc,const CString strArg1);
  bool CallJScript(const CString strFunc,const CString strArg1,
                   const CString strArg2);
  bool CallJScript(const CString strFunc,const CString strArg1,
                   const CString strArg2,const CString strArg3);
  bool CallJScript(const CString strFunc,const CStringArray& paramArray);


  CComPtr<IHTMLDocument2> m_spDoc;


Calling technique

The above mentioned technique can be split into the following steps:

  • Getting a pointer to the IHTMLDocument2 interface.
  • Getting IDispatch for the JavaScript object in the HTML document.
  • Getting the DISPID for the given name of the JavaScript function.
  • Putting the parameters to the DISPPARAM structure.
  • Calling the JavaScript function by using the Invoke method of the IDispatch interface.

Here is an example of getting an IDispatch pointer to the JavaScript objects:

bool CWebPage::GetJScript(CComPtr<IDispatch>& spDisp)
  HRESULT hr = m_spDoc->get_Script(&spDisp);
  return SUCCEEDED(hr);

And here is the final function to call JavaScript:

CComVariant CWebPage::CallJScript(const CString strFunc,
                                  const CStringArray& paramArray)
  //Getting IDispatch for Java Script objects
  CComPtr<IDispatch> spScript;
    ShowError("Cannot GetScript");
    return false;
  //Find dispid for given function in the object
  CComBSTR bstrMember(strFunc);
  DISPID dispid = NULL;
  HRESULT hr = spScript->GetIDsOfNames(IID_NULL,&bstrMember,1,
    return false;
  const int arraySize = paramArray.GetSize();
  //Putting parameters  
  DISPPARAMS dispparams;
  memset(&dispparams, 0, sizeof dispparams);
  dispparams.cArgs      = arraySize;
  dispparams.rgvarg     = new VARIANT[dispparams.cArgs];
  dispparams.cNamedArgs = 0;
  for( int i = 0; i < arraySize; i++)
    CComBSTR bstr = paramArray.GetAt(arraySize - 1 - i); // back reading
    dispparams.rgvarg[i].vt = VT_BSTR;
  EXCEPINFO excepInfo;
  memset(&excepInfo, 0, sizeof excepInfo);
  CComVariant vaResult;
  UINT nArgErr = (UINT)-1;  // initialize to invalid arg
  //Call JavaScript function         
  hr = spScript->Invoke(dispid,IID_NULL,0,
  delete [] dispparams.rgvarg;
    return false;
  return vaResult;

Notes about the demo

To call a JavaScript function from the demo, you should select a function in the tree in the left window. After this, press the "!" button on the menu bar.


  • July 07, 2011: Updated download files.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Eugene Khodakovsky
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

Questionhow to pass userdefined data type to javascript function such as struct ? Pin
Member 222813620-Oct-09 20:56
memberMember 222813620-Oct-09 20:56 
GeneralGetIDsOfNames return Unknown name Pin
Dabara26-Aug-09 3:58
memberDabara26-Aug-09 3:58 
QuestionWhat about cross-platform? Pin
ComaWhite8613-Dec-08 22:33
memberComaWhite8613-Dec-08 22:33 
Generalcalling java from c++ Pin
kioo05093-Oct-08 17:14
memberkioo05093-Oct-08 17:14 
GeneralRe: calling java from c++ Pin
Member 470826628-May-10 5:13
memberMember 470826628-May-10 5:13 
QuestionHi can anybody help me Pin
srinileo23-Sep-08 15:46
membersrinileo23-Sep-08 15:46 
GeneralIHTMLDocument without window Pin
Muran26-Aug-08 0:52
memberMuran26-Aug-08 0:52 
GeneralRe: IHTMLDocument without window Pin
Muran26-Aug-08 2:27
memberMuran26-Aug-08 2:27 
After searching i found the key.
The problem is that html is not loaded immediatly..
So I just processing message queue until readyState != complete.
using the next function
bool ProcessMessage()<br />
{ <br />
	MSG msg; <br />
<br />
	BOOL res = PeekMessage( &msg, 0, 0, 0, PM_NOREMOVE);<br />
<br />
	if( !res || <br />
		( WM_QUIT == msg.message ) ) <br />
		return false;<br />
<br />
	TranslateMessage(&msg); <br />
	DispatchMessage(&msg);<br />
<br />
	PeekMessage( &msg, 0, 0, 0, PM_REMOVE);<br />
<br />
	return true;<br />

this solution is not ideal, but I don't have any other Smile | :)
GeneralRe: IHTMLDocument without window Pin
Dabara26-Aug-09 4:25
memberDabara26-Aug-09 4:25 
QuestionHow to call external JavaScript ? Pin
naren_code21-Jun-07 4:48
membernaren_code21-Jun-07 4:48 
AnswerRe: How to call external JavaScript ? Pin
bumbumtrack2-Jul-07 19:52
memberbumbumtrack2-Jul-07 19:52 
Generalsupport for firefox Pin
vikram19798-Aug-06 4:04
membervikram19798-Aug-06 4:04 
GeneralDebug Informatoion corrupt Pin
Adeel68821-Jun-06 21:22
memberAdeel68821-Jun-06 21:22 
QuestionReverse task, how to call C++ function from JavaScript? Pin
M A V21-Jun-06 14:42
memberM A V21-Jun-06 14:42 
AnswerRe: Reverse task, how to call C++ function from JavaScript? Pin
jamesmhall30-Mar-07 4:05
memberjamesmhall30-Mar-07 4:05 
AnswerRe: Reverse task, how to call C++ function from JavaScript? Pin
www.add-your-page.com8-Oct-08 4:26
memberwww.add-your-page.com8-Oct-08 4:26 
GeneralRe: Reverse task, how to call C++ function from JavaScript? Pin
M A V8-Oct-08 4:58
memberM A V8-Oct-08 4:58 
GeneralRe: Reverse task, how to call C++ function from JavaScript? Pin
markhatsell5-Oct-10 5:55
membermarkhatsell5-Oct-10 5:55 
AnswerRe: Reverse task, how to call C++ function from JavaScript? Pin
M A V5-Oct-10 8:13
memberM A V5-Oct-10 8:13 
GeneralRe: Reverse task, how to call C++ function from JavaScript? Pin
markhatsell6-Oct-10 9:53
membermarkhatsell6-Oct-10 9:53 
AnswerRe: Reverse task, how to call C++ function from JavaScript? Pin
Sergey Alexander Gynech9-Jul-11 12:58
memberSergey Alexander Gynech9-Jul-11 12:58 
QuestionHow to get the result Pin
www.add-your-page.com16-May-06 10:07
memberwww.add-your-page.com16-May-06 10:07 
GeneralBUG, then calling JavaScript Pin
MicroCell13-Apr-06 22:06
memberMicroCell13-Apr-06 22:06 
GeneralHOWTO: Return value from C++ function to JavaScript Pin
Syed Khasim28-Mar-06 4:20
memberSyed Khasim28-Mar-06 4:20 
GeneralMemory leak while dealing parameters. Pin
Kim Moung Soo9-Mar-06 20:29
memberKim Moung Soo9-Mar-06 20:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180515.1 | Last Updated 7 Jul 2011
Article Copyright 2002 by Eugene Khodakovsky
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid