1.在APP的InitInstance()函数中加入AfxEnableControlContainer();以支持ole控件;
2.在CDHtmlDialog::OnInitDialog()中加入SetExternalDispatch(GetIDispatch(TRUE));
3.通过以下函数实现调用js函数:
BOOL CDHtmlDialog::CallJscript(const CString strFunc, _variant_t* pVarResult) { CStringArray paramArray; return CallJscript(strFunc,paramArray,pVarResult); } BOOL CDHtmlDialog::CallJscript(const CString strFunc,const CString strArg1,_variant_t* pVarResult) { CStringArray paramArray; paramArray.Add(strArg1); return CallJscript(strFunc,paramArray,pVarResult); } BOOL CDHtmlDialog::CallJscript(const CString strFunc, const CStringArray& paramArray,_variant_t* pVarResult) { CComPtr<IDispatch> spScript; if(!GetJscript(spScript)) { MessageBox("函数GetJScrip调用失败!"); return FALSE; } CComBSTR bstrFunc(strFunc); DISPID dispid = NULL; HRESULT hr = spScript->GetIDsOfNames(IID_NULL,&bstrFunc,1, LOCALE_SYSTEM_DEFAULT,&dispid); if(FAILED(hr)) { //MessageBox(GetSystemErrorMessage(hr)); return FALSE; } INT_PTR arraySize = paramArray.GetSize(); DISPPARAMS dispparams; memset(&dispparams, 0, sizeof dispparams); dispparams.cArgs = (UINT)arraySize; dispparams.rgvarg = new VARIANT[dispparams.cArgs]; for( int i = 0; i < arraySize; i++) { CComBSTR bstr = paramArray.GetAt(arraySize - 1 - i); // back reading bstr.CopyTo(&dispparams.rgvarg[i].bstrVal); dispparams.rgvarg[i].vt = VT_BSTR; } dispparams.cNamedArgs = 0; EXCEPINFO excepInfo; memset(&excepInfo, 0, sizeof excepInfo); _variant_t vaResult; UINT nArgErr = (UINT)-1; // initialize to invalid arg hr = spScript->Invoke(dispid,IID_NULL,0, DISPATCH_METHOD,&dispparams,&vaResult,&excepInfo,&nArgErr); delete [] dispparams.rgvarg; if(FAILED(hr)) { //MessageBox(GetSystemErrorMessage(hr)); return FALSE; } if(pVarResult) { *pVarResult = vaResult; } return TRUE; } BOOL CDHtmlDialog::GetJscript(CComPtr<IDispatch>& spDisp) { if( m_spHtmlDoc==NULL ) return FALSE; HRESULT hr = m_spHtmlDoc->get_Script(&spDisp); ATLASSERT(SUCCEEDED(hr)); return SUCCEEDED(hr); }
4.调用实例:
CallJscript("alert","test");