本文是在C++取得JavaScript的返回值使用,与之前的《JavaScript call from C++ 》(C++调用JavaScript)相反, JavaScript call from C++ 是在C++中将值传给JavaScript使用。
- From : Francesco Vitale <francesco.vitale@xxxxxxxxx >
- Date : 21 May 2007 08:46:34 -0700
对不起,我错了。我应当这样写:我想知道怎么得到JavaScript函数的返回值。
在C++中调用JavaScript并不简单,因为我知道,你必须得用COM/OLE做这事情。
像ATL中CComPtr这样智能指针以及MFC中一些类似COleDispatchDrive类或许可以帮很大忙。
你将可以发现一些可能对你有用的函数。
在我的机器上测试成功了,这个测试网页你可以在接下来的C++函数代码中找到。
这仅仅调用一个返回double值的JavaScript函数,然后将值显示在MessageBox中。
基本的思想是从得到从CHtmlView继承的类中得到IHTMLDocument2接口。注意,GetHtmlDocument()方法放回一个IDispatch,所以你必须得用QueryInterface从IDispatch得到IHTMLDocument2接口。
一旦你得到了IHTMLDocument2接口,你可通过IHTMLDocument2::get_Scrip方法进入脚本引擎,然后用经典的IDispatch机制关联脚本引擎来调用JavaScript函数。
代码如下:
我用于测试的JavaScript函数网页如下。
MrAsm
首先谢谢你的所做的工作,不幸地是你写HTML代码不是我需要处理的那种。
以下是我的HTML代码:
太好了,这个JavaScript可设置一个值,我之前从来没有见过这样的功能,并且我尝试得到"I_have_to_get_this_value"。现在我必须假设我之前的问题不知何种原因未完成。我希望我已经解决了。
十分感谢!
以下是原文,请参考,翻译错误以及不准确的地方,还望各位提出,谢谢!
- From : Francesco Vitale <francesco.vitale@xxxxxxxxx >
- Date : 21 May 2007 08:46:34 -0700
On 21 Mag, 16:47, MrAsm <m...@xxxxxxx> wrote:
On 21 May 2007 05:16:31 -0700, Francesco Vitale
<francesco.vit...@xxxxxxxxx> wrote:
Sorry... I went wrong:
I should have written: I wonder how to get the values returned by a
javascript function
Calling JavaScript from C++ it's not trivial, because - for what I
know - you have to do the job using COM/OLE.
ATL smart pointers like CComPtr and some MFC classes like
COleDispatchDriver may help a bit.
Here you can find some code that might be useful for you.
I tested it on my machine (using a test web page you can find after
the C++ function code) and it works.
It just calls a JavaScript function which returns a double value, and
then displays the value in MessageBox.
The basic idea is to get the IHTMLDocument2 interface from the
CHtmlView derived class (note that GetHtmlDocument() method returns an
IDispatch, so you have to QueryInterface from IDispatch to get the
IHTMLDocument2 interface).
Once you have the IHTMLDocument2 interface you can access the Script
engine (via IHTMLDocument2::get_Script method), and then "Invoke" the
JavaScript function using the classical Invoke mechanism of IDispatch
associated to Script engine.
The code follows:
<CODE language="C++">
void OnTestCallJavascript( CMyHtmlView * pHtmlView )
{
// pHtmlView is a pointer to CHtmlView derived class
//
// Hungarian Notation here:
//
// sp : smart-pointer (CComPtr)
//
// COM operations return code
HRESULT hr;
//
// Access the IHTMLDocument2 interface from the HTML view
//
// Get IDispatch for HTML Document from HTML view
CComPtr< IDispatch > spDispatch = pHtmlView->GetHtmlDocument();
// Get IHTMLDocument2 interface from the above IDispatch
CComPtr< IHTMLDocument2 > spDocument;
hr = spDispatch->QueryInterface(
IID_IHTMLDocument2,
(void **) &spDocument );
if ( FAILED(hr) )
{
MessageBox( _T("Can't get IHTMLDocument2 interface."),
_T("*** ERROR ***"),
MB_OK|MB_ICONERROR );
return;
}
//
// Given the IHTMLDocument2, access the Script Engine
//
// Get script engine from HTML document
CComPtr< IDispatch > spScript;
hr = spDocument->get_Script( &spScript );
if ( FAILED(hr) )
{
MessageBox( _T("Can't access the Script Engine."),
_T("*** ERROR ***"),
MB_OK|MB_ICONERROR );
return;
}
//
// Call the JavaScript function
//
//
// In this example, the function name is "testReturnValue";
// the function takes no argument, and
// returns a double precision floating-point.
//
// Name of the function to call
const CString strFunctionName = "testReturnValue";
// Convert it to COM BSTR string
CComBSTR bstrFunction( strFunctionName );
// ID associated to function
DISPID dispid = NULL;
// Map the function name to its numerical ID
hr = spScript->GetIDsOfNames(
IID_NULL, // (reserved)
&bstrFunction, // name to get ID of
1, // only 1 name
LOCALE_SYSTEM_DEFAULT, // default locale context
&dispid // will return the ID associated
// to given name
);
if ( FAILED(hr) )
{
MessageBox( _T("Can't get the ID of function."),
_T("*** ERROR ***"),
MB_OK|MB_ICONERROR );
return;
}
// Return value of the function (stored in OLE variant)
COleVariant result;
// This function takes no argument
const BYTE noArgument[] = { '/0' };
// Use the helper class to invoke the function
COleDispatchDriver dispatchDriver(
spScript, // Script Engine
FALSE // Don't automatically release it
);
dispatchDriver.InvokeHelper(
dispid, // Function ID
DISPATCH_METHOD, // We're invoking a method
VT_VARIANT, // Type of return value
(void *) &result, // Where to store return value
noArgument // Argument descriptions
);
// NOTE: InvokeHelper may throw exceptions on error...
// So we could catch them here or in other context...
// A different approach would be to use spScript->Invoke
// and prepare DISPPARAMS structures, but is is a bit
// more complicated...
//
// Convert the OLE variant value to C++ double,
// and show it
//
double dResult = result.dblVal;
CString msg;
msg.Format( _T("Function returned: %g"), dResult );
MessageBox( msg );
}
</CODE>
And this is the web page with JavaScript I used for test:
<CODE language="HTML">
<html>
<head>
<title>JavaScript called from C++</title>
<script type="text/javascript">
<!--
function testReturnValue() {
alert("testReturnValue called");
return 3.1415;
}
// -->
</script>
</head>
<body>
<h1>Test JavaScript from C++</h1>
<a href="#" οnclick="testReturnValue();">Test function</a>
</body>
</html>
</CODE>
MrAsm
First of all I'd like to thank you for the effort you showed.
Unfortunately the kind of HTML code I have to handle is not like the
one you meant.
Here follows my HTML code:
<HTML>
<BODY οncοntextmenu="return false">
<script>
window.returnValue = "I_have_to_get_this_value"
function closeMyPage(){
self.close();
}
</script>
<center>
Click on this button to close the window <INPUT TYPE="button"
VALUE="Close" onClick="closeMyPage()">
</center>
</BODY>
</HTML>
Well... what can I say... the javascript is setting a value (...I
never saw anything like this before yesterday!!)
and yes... I'm trying to get the "I_have_to_get_this_value".
Now I have to suppose my previous question was somehow uncomplete.
I hope I've been clearer now.
Thank you very much!!!
fRA