Call JavaScript Functions in COM components
The requirement is very simple, that is, COM component A runs in IE. using JavaScript (JS) to call method longcalc () of A is a time-consuming operation, the current IE progress must be notified. This requires the use of the callback function, set its name to scriptcallbackfunc. This technology is simple:
1 component side (C ++)
The method of component A is defined in IDL:
[ID (2)] hresult longcalc ([in] Double V1, [in] Double V2, [in, optional] variant scriptcallback );
Method Implementation of component:
// Assume that the callback prototype is:
// Scriptcallbackfunc (long ncurrentprogress, long ntotalprogress, BSTR bstrprogressname );
// This method is implemented by the JS script
Stdmethodimp CA: longcalc (double V1, double V2, variant scriptcallback)
{
Ccomptr <idispatch> spcallback;
If (scriptcallback. Vt = vt_dispatch)
Spcallback = scriptcallback. pdispval;
// parameter preparation
ccomvariant varresult;
ccomvariant avarparams [3];
avarparams [0] = "start to calculate shares "; // bstrprogressname
avarparams [0]. vt = vt_bstr;
avarparams [1] = 100; // ntotalprogress
avarparams [1]. vt = vt_i4;
avarparams [2] = 0; // ncurrentprogress
avarparams [2]. vt = vt_i4;
dispparams Params = {avarparams, null, 3, 0};
If (spcallback)
Spcallback-> invoke (0,
Iid_null,
Locale_user_default,
Dispatch_method,
& Params, & varresult, null, null );
Bool bfinished = false;
While (! Bfinished)
{
// Computing...
Sleep (1000 );
V1 = V1 + V2;
// Callback customer
If (spcallback)
{
Avarparams [0] = "calculating stock ...";
Avarparams [2] = 0;
Spcallback-> invoke (0,
Iid_null,
Locale_user_default,
Dispatch_method,
& Params, & varresult, null, null );
}
If (...)
Bfinished = true;
} // While OK!
Return s_ OK;
}
2. Client (JS)
<Script language = "JavaScript">
<! --
// The callback prototype is scriptcallbackfunc.
Function scfdisplayprogress (ncurrentprogress, ntotalprogress, bstrprogressname)
{
Window. Status = bstrprogressname + ":" + (ncurrentprogress * 100/totalprogress );
}
// Create a component and execute longcalc
VaR obja = new activexobject ("mycom. ");
// Use callback: The progress is displayed in the IE status bar during execution.
Obja. longcalc (100,200, scfdisplayprogress );
// Do not use callback
Obja. longcalc (100,200 );
// -->
</SCRIPT>
3 Description
This technique is only applicable to scripts. Not suitable for VB and C ++ customers.
This technology has nothing to do with connection points and events.
This method is widely used by Microsoft xml dom objects.