Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've been trying to get the return value of a Javascript function from within C++ using IHTMLWindow2::execScript however, it never seems to work. The following is an example of what I am trying to perform.

C++ Code:
C++
CComPtr<IHTMLWindow2> win;
doc2->get_parentWindow( &win);
CComVariant empty;

CComBSTR fullScript = L"function testFunction(){";
fullScript += L"return 2254;";
fullScript += L"}";
fullScript += L"testFunction();";

win->execScript(fullScript.m_str, L"JAVASCRIPT", &empty);


The CComVariant empty is always empty. All the examples out there use INVOKE to call a javascript function which is already embedded within the HTML page. In my case, I need to get the return value of a Javascript function on the fly that isn't embedded within my HTML page.

Any ideas? Thanks in advance!
Posted

The article JavaScript-call-from-C enlights how to work with javscript from C++. But Microsoft says since IE 11: "Starting with IE11, use eval"...
 
Share this answer
 
Comments
Daroosh 19-Jan-15 10:04am    
Thanks a lot KarstenK however, this article and almost all the other articles describe how to call JS functions that are already embedded within the page's HTML source. I don't need that, I need to call JS functions on the fly that aren't embedded within the HTML source.
After searching around for a couple of hours, I managed to make it run as required. The following is a snippet for how to make it work (runs within DOCUMENTCOMPLETE):

C++
// Get IHTMLWindow
CComPtr<ihtmlwindow2> win;
doc2->get_parentWindow( &win);

if (win == NULL) return E_FAIL;
			
// Get IHTMLWindow dispatch
CComDispatchDriver dispWindow;
win->QueryInterface(&dispWindow);
			
if (dispWindow == NULL) return E_FAIL;
			
// Define JAVAScript
CComBSTR fullScript = L"function testFunction(){";
fullScript += L"alert('JS function called!')";
fullScript += L"return  true;";
fullScript += L"}testFunction();";
CComVariant script(fullScript.m_str);
CComVariant result;
			
// Execute JavaSctript
dispWindow.Invoke1(L"eval", &script, &result);
			
result.ChangeType(VT_BSTR);
			
// Print Result
LOG(L"%s", result.bstrVal);
</ihtmlwindow2>
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900