Several methods for VC to call javascript of recommendation

  • 2021-07-09 06:52:45
  • OfStack

Type 1: Called through execScript. Although this method is easy to operate, it cannot get 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);

Type 2: Find the script function name with GetIDsOfNames, and then call it. This method can return results, with return values. However, the system functions of js, such as eval, cannot be called.


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 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;
  }
  
  *pVarResult = vaResult;
  return TRUE;
}

In actual use, it may be that one page was visited (Navigate) first. Then, make a few js calls to the page in VC and retrieve the results. It is possible that this js calls a function that is not available on this page. You can use eval (1 js statements) to call functions that are not in the page, but eval is not supported by the above two methods.

Type 3: 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 you that you do not have permission.)

First define one: IScriptControlPtr, and then call m_spHtmlDoc under 1 in OnDocumentComplete- > get_parentWindow( & m_pHtmlWindow);

IScriptControlPtr- > AddObject("window", m_pHtmlWindow, VARIANT_TRUE);

Type 3 requires import "msscript. ocx"


Related articles: