C++如何调用JS函数

 

Introduction

Sometimes when you are using the IE Browser Control inside of a C++ application, you need to get access to the HTML elements. We can do it by using standard COM objects likeIWebBrowser2, IHTMLDocument2, etc. By this method, we can easily implement features like click button, click anchor, get input string, get HTML text, etc. Unfortunately, Microsoft did not provide similar objects for JavaScript. At any case, to make control for a JavaScript object inside of an HTML page is possible by using the traditional COM approach. This article describes the classCWebPage which allows to do it and a technique to call a JavaScript function from C++ code.

How to do

As a result of using the presented class, it will be easy to call any JavaScript function from C++ code. For implementing this feature, we should get a pointer to theIHTMLDocument2 interface. If we are using the CHtmlView class from MFC, we can get one by using the member functionCHtmlView::GetHtmlDocument(). In the case of using IWebBrowser orIWebBrowser2 components, the function get_Document will bring us the desired interface. Here is an example:

CComPtr<IDispatch> spDisp = CHtmlView::GetHtmlDocument();
m_webPage.SetDocument(spDisp);

The rest of the things will be done by the CWebPage class. Here is an example of a JavaScript call without parameters:

m_webPage.CallJScript("Welcome");

An example of a JavaScript call with two parameters will looks like:

m_webPage.CallJScript("Miltiply","2.34","3.32");

The class implementation

class CWebPage
{
public:
  CWebPage();
  virtual ~CWebPage();

  bool SetDocument(IDispatch* pDisp);
  LPDISPATCH GetHtmlDocument() const;
  const CString GetLastError() const;
  bool GetJScript(CComPtr<IDispatch>& spDisp);
  bool GetJScripts(CComPtr<IHTMLElementCollection>& spColl);
  CString ScanJScript(CString& strAText,CStringArray& args);

  bool CallJScript(const CString strFunc);
  bool CallJScript(const CString strFunc,const CString strArg1);
  bool CallJScript(const CString strFunc,const CString strArg1,
                   const CString strArg2);
  bool CallJScript(const CString strFunc,const CString strArg1,
                   const CString strArg2,const CString strArg3);
  bool CallJScript(const CString strFunc,const CStringArray& paramArray);

protected:

  CComPtr<IHTMLDocument2> m_spDoc;

};

Calling technique

The above mentioned technique can be split into the following steps:

  • Getting a pointer to the IHTMLDocument2 interface.
  • Getting IDispatch for the JavaScript object in the HTML document.
  • Getting the DISPID for the given name of the JavaScript function.
  • Putting the parameters to the DISPPARAM structure.
  • Calling the JavaScript function by using the Invoke method of theIDispatch interface.

Here is an example of getting an IDispatch pointer to the JavaScript objects:

bool CWebPage::GetJScript(CComPtr<IDispatch>& spDisp)
{
  HRESULT hr = m_spDoc->get_Script(&spDisp);
  ATLASSERT(SUCCEEDED(hr));
  return SUCCEEDED(hr);
}

And here is the final function to call JavaScript:

CComVariant CWebPage::CallJScript(const CString strFunc,
                                  const CStringArray& paramArray)
{
  //Getting IDispatch for Java Script objects
  CComPtr<IDispatch> spScript;
  if(!GetJScript(spScript))
  {
    ShowError("Cannot GetScript");
    return false;
  }
  //Find dispid for given function in the object
  CComBSTR bstrMember(strFunc);
  DISPID dispid = NULL;
  HRESULT hr = spScript->GetIDsOfNames(IID_NULL,&bstrMember,1,
                            LOCALE_SYSTEM_DEFAULT,&dispid);
  if(FAILED(hr))
  {
    ShowError(GetSystemErrorMessage(hr));
    return false;
  }
  
  const int arraySize = paramArray.GetSize();
  //Putting parameters  
  DISPPARAMS dispparams;
  memset(&dispparams, 0, sizeof dispparams);
  dispparams.cArgs      = arraySize;
  dispparams.rgvarg     = new VARIANT[dispparams.cArgs];
  dispparams.cNamedArgs = 0;
  
  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;
  }
  EXCEPINFO excepInfo;
  memset(&excepInfo, 0, sizeof excepInfo);
  CComVariant vaResult;
  UINT nArgErr = (UINT)-1;  // initialize to invalid arg
  //Call JavaScript function         
  hr = spScript->Invoke(dispid,IID_NULL,0,
                        DISPATCH_METHOD,&dispparams,
                        &vaResult,&excepInfo,&nArgErr);
  delete [] dispparams.rgvarg;
  if(FAILED(hr))
  {
    ShowError(GetSystemErrorMessage(hr));
    return false;
  }
  return vaResult;
}
Qt QML是一种基于JavaScript的声明式语言,用于快速构建跨平台的用户界面。它有时需要与C++代码交互,因为C++可以提供更高性能和更底层的功能。 要在Qt QML中调用C函数,需要进行以下步骤: 1. 创建一个继承自QObjectC++类,并在其中定义所需的函数。这些函数需要使用Q_INVOKABLE宏进行标记,以便在QML中调用。 ```cpp // MyFunctions.h #include <QObject> class MyFunctions: public QObject { Q_OBJECT public: explicit MyFunctions(QObject *parent = nullptr); Q_INVOKABLE void myFunction(); }; ``` 2. 在QML文件中导入C++类,并使用其实例调用函数。 ```qml import MyFunctions 1.0 Window { // ... Button { text: "调用C函数" onClicked: { MyFunctions.myFunction(); } } // ... } ``` 3. 在C++代码中将该类注册到QML引擎中。 ```cpp // main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include "MyFunctions.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qmlRegisterType<MyFunctions>("MyFunctions", 1, 0, "MyFunctions"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); } ``` 通过以上步骤,就可以在Qt QML中成功调用C函数了。在按钮点击事件中调用C++类的函数,可以在C++代码中执行所需的操作,并将结果返回到QML界面中进行展示。这种方式可以实现Qt QML框架与C++高性能功能的结合,使得开发者能够更好地发挥Qt的优秀特性和灵活性。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值