1 首先 .h 文件中定义:
2
3 CComPtr<IHTMLWindow2> m_sphtmlWnd;
4 CComPtr<IHTMLDocument2> m_spHtmlDoc;
5
6
7
8 //方法1 可以取得返回值。。。。。
9
10 //调用方法示例:stringArray为传入参数列表,getSum为js函数,pVarResult 为返回值
11
12 /* CStringArray stringArray;
13 stringArray.RemoveAll();
14 stringArray.SetSize(5);
15 stringArray[0].Format(L"%d",m_poiStart.x);
16 stringArray[1].Format(L"%d",m_poiStart.y);
17 stringArray[2].Format(L"%d",m_poiEnd.x);
18 stringArray[3].Format(L"%d",m_poiEnd.y);
19 stringArray[4].Format(L"%d",a + 1);
20 CComVariant pVarResult = CallJScript(L"getSum", stringArray);*/
21
22 bool Cems_mysql_appView::GetJScript(CComPtr<IDispatch>& spDisp)
23 {
24 m_spHtmlDoc = (IHTMLDocument2*)(GetHtmlDocument());
25 if(m_spHtmlDoc == NULL)
26 {
27 return false;
28 }
29 HRESULT hr = m_spHtmlDoc->get_Script(&spDisp);
30 ATLASSERT(SUCCEEDED(hr));
31 return SUCCEEDED(hr);
32 }
33
34 CComVariant Cems_mysql_appView::CallJScript(const CString strFunc,const CStringArray& paramArray)
35 {
36 //Getting IDispatch for Java Script objects
37 CComPtr<IDispatch> spScript;
38 if(!GetJScript(spScript))
39 {
40 return false;
41 }
42 //Find dispid for given function in the object
43 CComBSTR bstrMember(strFunc);
44 DISPID dispid = NULL;
45 HRESULT hr = spScript->GetIDsOfNames(IID_NULL,&bstrMember,1,
46 LOCALE_SYSTEM_DEFAULT,&dispid);
47 if(FAILED(hr))
48 {
49 return false;
50 }
51
52 const int arraySize = paramArray.GetSize();
53 //Putting parameters
54 DISPPARAMS dispparams;
55 memset(&dispparams, 0, sizeof dispparams);
56 dispparams.cArgs = arraySize;
57 dispparams.rgvarg = new VARIANT[dispparams.cArgs];
58 dispparams.cNamedArgs = 0;
59
60 for( int i = 0; i < arraySize; i++)
61 {
62 CComBSTR bstr = paramArray.GetAt(arraySize - 1 - i);
63 // back reading
64 bstr.CopyTo(&dispparams.rgvarg[i].bstrVal);
65 dispparams.rgvarg[i].vt = VT_BSTR;
66 }
67 EXCEPINFO excepInfo;
68 memset(&excepInfo, 0, sizeof excepInfo);
69 CComVariant vaResult;
70 UINT nArgErr = (UINT)-1; // initialize to invalid arg
71 //Call JavaScript function
72 hr = spScript->Invoke(dispid,IID_NULL,0,DISPATCH_METHOD,&dispparams,&vaResult,&excepInfo,&nArgErr);
73 delete [] dispparams.rgvarg;
74 if(FAILED(hr))
75 {
76 return false;
77 }
78 return vaResult;
79 }
80
81
82
83 //方法2
84
85 /*调用方法,不必多说。
86
87 CString str;
88 str.Format(L"getSum(%d,%d,%d,%d,%d)",m_poiStart.x,m_poiStart.y,m_poiEnd.x,m_poiEnd.y,a+1);
89 ExecScript(str);
90
91 */
92 HRESULT Cems_mysql_appView::ExecScript(CString strjs)
93 {
94 HRESULT hr;
95 m_spHtmlDoc = (IHTMLDocument2*)(GetHtmlDocument());
96 if(m_sphtmlWnd == NULL)
97 {
98 hr = m_spHtmlDoc->get_parentWindow(&m_sphtmlWnd);//获取脚本指针
99 }
100 CComBSTR bstrjs = strjs.AllocSysString();
101 CComBSTR bstrlan = SysAllocString(L"javascript");
102 VARIANT varRet;
103 hr = m_sphtmlWnd->execScript(bstrjs, bstrlan, &varRet);
104 //m_sphtmlWnd = NULL;
105 return 1;
106 }
107