Javascript – Call a JavaScript function from C++


I have a CDHTMLDialog, with which I have 2 HTML pages and a .js file with a few fairly simple functions.

I would like to be able to call one of the JS functions from my program with a simple data type passed with it. e.g. MyFunc(int). Nothing needs to be returned.

I would appreciate any guidance on how I go about this,


Edit: Thanks to CR for his answer, and everyone else who submitted there ideas too.

Something a little like this worked in the end (stripped a little error handling from it for clarity):

void callJavaScriptFunc(int Fruit)
    HRESULT hRes;
    CString FuncStr;
    CString LangStr = "javascript";
    VARIANT vEmpty = {0};

    CComPtr<IHTMLDocument2> HTML2Doc;
    CComPtr<IHTMLWindow2> HTML2Wind;

    hRes = GetDHtmlDocument(&HTML2Doc);
    hRes = HTML2Doc->get_parentWindow(&HTML2Wind);

    if( Fruit > 0 ) 
        FuncStr = "myFunc(808)";  // Javascript parameters can be used
        hRes = HTML2Wind->execScript(FuncStr.AllocSysString(), LangStr.AllocSysString(), &vEmpty);

Best Solution

Easiest approach would be to use the execScript() method in the IHTMLWindow2 interface.

So you could get the IHTMLDocument2 interface from your CDHTMLDialog by calling GetDHtmlDocument, then get the parentWindow from IHTMLDocument2. The parent window will have the IHTMLWindow2 interface that supports execScript().

There might be an easier way to get the IHTMLWindow2 interface from your CDHTMLDialog but I'm used to working at a lower level.