The first type: call through execScript. Although this method is easy to operate, it cannot obtain the return value.
m_spHtmlDoc->get_parentWindow(&m_pHtmlWindow);VARIANT ret;ret.vt = VT_EMPTY;BSTR bstr = sScript.AllocSysString();bRet = m_pHtmlWindow->execScript(bstr, L"javascript", &ret);::SysFreeString(bstr);sRet = CString(ret);
The second type: first use GetIDsOfNames to find the script function name, and then call it. This method can return the result and have a return value. But it is impossible to call system functions of js, such as eval.
BOOL CDhtmlDlgWindow::CallJScript(const CString strFunc, const CStringArray& paramArray, CComVariant* pVarResult){ CComPtr spScript; if (NULL==m_spHtmlDoc) { return FALSE; } HRESULT hr; hr = m_spHtmlDoc->get_Script(&spScript); if(!SUCCEEDED(hr)) { return FALSE; } CComBSTR bstrMember(strFunc); DISPID dispid = NULL; hr = spScript->GetIDsOfNames(IID_NULL,&bstrMember,1, LOCALE_SYSTEM_DEFAULT,&dispid); if(FAILED(hr)) { return FALSE; } const int arraySize = paramArray.GetSize(); DISPPARAMS dispparams; memset(&dispparams, 0, sizeof dispparams); dispparams.cArgs = 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 exceptionInfo; memset(&excepInfo, 0, sizeof exceptionInfo); CComVariant 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)) { return FALSE; } *pVarResult = vaResult; return TRUE;}When actually using it, you may have accessed a page first. Then, make some js calls to this page in VC and retrieve the result. It is possible that the function called by this js is not available in this page. Generally, you can use the form of eval (some js statements) to call functions that are not in the page, but now neither of the above methods supports eval.
The third type: get the current document context through IScriptControl, and then call the IScriptControl::raw_Eval operation. (You can only use raw_Eval. Using the Eval method will prompt that there is no permission.)
First define one: IScriptControlPtr, and then call m_spHtmlDoc->get_parentWindow(&m_pHtmlWindow);
IScriptControlPtr->AddObject("window", m_pHtmlWindow, VARIANT_TRUE);
The third type requires import "msscript.ocx"
The above several methods (recommended) of VC calling javascript are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.