Web Browser控件,C++调用JS

void CcaterpDlg::ShowOrHideAudioBTN( bool bShow )
{
	CString strJsName = _T("showOrHideAudio");
	CStringArray csa;
	CComVariant VarResult;
	CString strJsParam = _T("0");
	if (bShow)
	{
		strJsParam = _T("1");
	}
	csa.Add(strJsParam);
	CallJScript(strJsName , csa, &VarResult );
}


BOOL CcaterpDlg::CallJScript( const CString strFunc, const CStringArray& paramArray,CComVariant* pVarResult )
{
	if (m_pWeb==NULL)
	{
		return FALSE;
	}

	CComPtr<IDispatch> spScript=NULL;
	if(!GetJScript(spScript))
	{
		LOG_ERROR(_T("Cannot GetScript"));
		return FALSE;
	}
	CComBSTR bstrMember(strFunc);
	DISPID dispid = NULL;
	HRESULT 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 excepInfo;
	memset(&excepInfo, 0, sizeof excepInfo);
	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;
	}

	if(pVarResult)
	{
		*pVarResult = vaResult;
	}
	return TRUE;
}

BOOL CcaterpDlg::GetJScript( CComPtr<IDispatch>& spDisp )
{
	if (m_pWeb==NULL)
	{
		return FALSE;
	}

	CComPtr<IHTMLDocument2> pHtmlDoc=NULL;
	CComPtr<IDispatch> spDocDisp;
	HRESULT hr;
	if(spDisp == NULL)
	{
		spDocDisp = m_pWeb->get_Document();

		if(spDocDisp)
		{
			hr = spDocDisp->QueryInterface(IID_IHTMLDocument2, (void**)&pHtmlDoc);
			if (SUCCEEDED(hr) && pHtmlDoc)
			{
				// get script
				hr = pHtmlDoc->get_Script(&spDisp);
				ATLASSERT(SUCCEEDED(hr));

			}
		}
	}
	ATLASSERT(SUCCEEDED(hr));
	return SUCCEEDED(hr);
}


你可能感兴趣的:(Web Browser控件,C++调用JS)