Communication between C++ and Javascript in Qt WebEngine(转载)

摘要:
page()->window.foo=webobj;
Communication between C++ and Javascript in Qt WebEngine
 January 31, 2018 0

As Qt WebKit is replaced by Qt WebEngine(you can refer to this postabout porting issues), accessing html elements from C++ directly becomes impossible. Many works originally done by QWebKit classes are now transferred to javascript. Javascript is used to manipulate web content. And you need to call runJavaScript from C++ code to run javascript on the web page loaded by QWebEngineView.To get web elements, a communication mechanism is invented to bridge the C++ world and the javascript world. The bridging mechanism is more than obtaining the values of web page elements. It provides the ways in which C++ code can call javascript functions, and javascript can invoke C++ functions as well.The values of variables can also be passed from C++ to javascript, and vice versa. Let’s consider the following application scenarios:

javascript code calls C++ function

C++ code should provide a class which contains the to-be-called function(as a slot), then register an object of this class to a QWebChannelobject, and set the web channel object to the web page object in the QWebEngineView

  1. class WebClass : public QObject
  2. {
  3. Q_OBJECT
  4. public slots:
  5. voidjscallme()
  6. {
  7. QMessageBox::information(NULL,"jscallme","I'm called by js!");
  8. }
  9. };
  10. WebClass *webobj = newWebClass();
  11. QWebChannel *channel = newQWebChannel(this);
  12. channel->registerObject("webobj", webobj);
  13. view->page()->setWebChannel(channel);

To invoke the C++ function jscallme, javascript should new an instance of QWebChannel object.

  1. new QWebChannel(qt.webChannelTransport,
  2. function(channel){
  3. var webobj = channel.objects.webobj;
  4. window.foo = webobj;
  5. });

QWebChannel is defined in qwebchannel.js(you can find this file in the example folder of Qt installation directory) so the script should be loaded first. In the function passed as the second parameter of function QWebChannel, the exposed object from C++ world(webobj in C++) channel.objects.webobj is assigned to the javascript variable webobj, and then assigned to window.foo so you can use foo elsewhere to refer to the object. After the function is executed, javascript can call the C++ slot function jscallme as follows:

  1. foo.jscallme();

Pass data from javascript to C++

We’ve known how to call C++ function from javascript. You should be able to figure out a way to pass data from javascript to C++, i.e., as parameter(s) of function. We re-implement jscallme as follows:

  1. voidjscallme(const QString &datafromjs)
  2. {
  3. QMessageBox::information(NULL,"jscallme","I'm called by js!");
  4. m_data=datafromjs;
  5. }

, and invoking of the function from js would be:

  1. foo.jscallme(somedata);

Note that the “const” before the parameter can not be omitted, otherwise, you will get the following error:
Could not convert argument QJsonValue(string, “sd”) to target type .

Although data can be passed as parameters of function, it would be more convenient if we can pass data by setting an attribute of an object like:

  1. foo.someattribute="somedata";

We expect after the code is executed, “somedata” will be stored in a member variable of the exposed object (webobj) in C++. This is done by delaring a qt property in C++ class:

  1. class WebClass : public QObject
  2. {
  3. Q_OBJECT
  4. Q_PROPERTY(QString someattribute MEMBER m_someattribute)
  5. public slots:
  6. voidjscallme()
  7. {
  8. QMessageBox::information(NULL,"jscallme","I'm called by js!");
  9. }
  10. private:
  11. QString m_someattribute;
  12. };

Now if you execute foo.someattribute=”somedata” in javascript, m_someattribute in C++ will be “somedata”.

Pass data from C++ to javascript

We can send data from C++ to javascript using signals. We emit a signal with the data to send as the parameter of the signal. Javascript must connect the signal to a function to receive the data.

  1. class WebClass : public QObject
  2. {
  3. Q_OBJECT
  4. Q_PROPERTY(QString someattribute MEMBER m_someattribute)
  5. public slots:
  6. voidjscallme()
  7. {
  8. QMessageBox::information(NULL,"jscallme","I'm called by js!");
  9. }
  10. voidsetsomeattribute(QString attr)
  11. {
  12. m_someattribute=attr;
  13. emit someattributeChanged(m_someattribute);
  14. }
  15. signals:
  16. voidsomeattributeChanged(QString & attr);
  17. private:
  18. QString m_someattribute;
  19. };
  1. var updateattribute=function(text)
  2. {
  3. $("#attrid").val(text);
  4. }
  5. new QWebChannel(qt.webChannelTransport,
  6. function(channel){
  7. var webobj = channel.objects.webobj;
  8. window.foo= webobj;
  9. webobj.someattributeChanged.connect(updateattribute);
  10. });

The line “webobj.someattributeChanged.connect(updateattribute)” connects the C++ signal someattributeChanged to the javascript function updateattribute. Note that although updateattribute takes one parameter “text”, we did not provide the parameter value in connect. In fact, we do not know the parameter value passed to updateattribute until the signal is received. The signal is accompanied by a parameter “attr” which is passed as the “text” parameter of updateattribute. Now, if you call webobj->setsomeattribute(“hello”), you will see the value of the html element with id “#attrid” is set to “hello”. Note that although we connect the member m_someattribute to the qt property someattribute in the above example, it is not a required step. The signal mechanism alone can realize the delivery of data.
We can make things even simpler by adding the NOTIFY parameter when declaring the someattribute property.

  1. class WebClass : public QObject
  2. {
  3. Q_OBJECT
  4. Q_PROPERTY(QString someattribute MEMBER m_someattribute NOTIFY someattributeChanged)
  5. public slots:
  6. voidjscallme()
  7. {
  8. QMessageBox::information(NULL,"jscallme","I'm called by js!");
  9. }
  10. signals:
  11. voidsomeattributeChanged(QString & attr);
  12. private:
  13. QString m_someattribute;
  14. };

Now, if you call webobj->setProperty(“someattribute”,”hello”) somewhere in C++, the signal “someattributeChanged” is automatically emitted and our web page gets updated.

C++ invokes javascript function

This is much straightforward compared with invoking C++ function from js. Just use runJavaScript passing the function as the parameter as follows:

  1. view->page()->runJavaScript("jsfun();",[this](const QVariant &v){qDebug()<<v.toString();});

It assumes the jsfun is already defined on your web page, otherwise, you have to define it in the string parameter. The return value is asynchronously passed to the lambda expression as the parameter v.

Now, back to the question raised at the beginning of the post: How to get the value of an html element in C++? It can be done as follows:

  1. view->page()->runJavaScript("function getelement(){return $('#elementid').val();} getelement();",[this](const QVariant &v){qDebug()<<v.toString();});

It uses jQuery functions so make sure jQuery lib is running on your web page.

免责声明:文章转载自《Communication between C++ and Javascript in Qt WebEngine(转载)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Tomcat启动时加载数据到缓存---web.xml中listener加载顺序(例如顺序:1、初始化spring容器,2、初始化线程池,3、加载业务代码,将数据库中数据加载到内存中)WebService(axis2),整合springmvc下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

java 识别图片相似度及图片是否相同

1.比较MD5值 判断图片是否相同 package com.zerdoor.util; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.util...

VS2015 之 常用快捷键

VS2015 之 常用快捷键 调试执行 F5,终止调试执行 Shift+F5 启动执行 Ctrl+F5 查找下一个 F3,查找上一个 Shift+F3 附加到进程 Ctrl+Alt+P,逐过程 F10,逐语句执行 F11 切换断点 F9(添加或取消断点) 运行至光标处 Ctrl+F10 跳出当前方法 Shift+F11 新建解决方案 Ctrl+Shift+...

pycharm常用配置详解

  PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、单元测试、版本控制。此外,该IDE提供了一些高级功能,以用于支持Django框架下的专业Web开发。 Windows版本下载地址:https://www.jetbrains....

.net 反编译利器 dnspy

Binaries Latest release: https://github.com/0xd4d/dnSpy/releases Latest build (possibly unstable): https://ci.appveyor.com/project/0xd4d/dnspy/build/artifacts Features Assembly...

JS 获取web sql 数据

var tbName="tableName"; var tdName=["id","th1","th2","th3"]; var strSQL="select * from "+tbName+" where id="+1; //从web sql数据库获取数据; function getWebSqlData(strSQL,tbName,tdName){...

网站日志流量分析系统之(日志埋点)

一、概述    日志埋点分为客户端和服务器端。参考并转自:https://www.cnblogs.com/hzhuxin/p/11152805.html,如有侵权,请联系删除。)   ①客户端埋点:支持 iOS、安卓、Web/H5、微信小程序,主要用于分析 UV、PV、点击量等基本指标。例:下图是Web端的埋点技术图:       ②服务器日志:采集后端业...