Communication between C++ and Javascript in Qt WebEngine(转载)
Communication between C++ and Javascript in Qt WebEngine
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
- class WebClass : public QObject
- {
- Q_OBJECT
- public slots:
- void jscallme()
- {
- QMessageBox::information(NULL,"jscallme","I'm called by js!");
- }
- };
- WebClass *webobj = new WebClass();
- QWebChannel *channel = new QWebChannel(this);
- channel->registerObject("webobj", webobj);
- view->page()->setWebChannel(channel);
To invoke the C++ function jscallme, javascript should new an instance of QWebChannel object.
- new QWebChannel(qt.webChannelTransport,
- function(channel){
- var webobj = channel.objects.webobj;
- window.foo = webobj;
- });
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:
- 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:
- void jscallme(const QString &datafromjs)
- {
- QMessageBox::information(NULL,"jscallme","I'm called by js!");
- m_data=datafromjs;
- }
, and invoking of the function from js would be:
- 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:
- 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:
- class WebClass : public QObject
- {
- Q_OBJECT
- Q_PROPERTY(QString someattribute MEMBER m_someattribute)
- public slots:
- void jscallme()
- {
- QMessageBox::information(NULL,"jscallme","I'm called by js!");
- }
- private:
- QString m_someattribute;
- };
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.
- class WebClass : public QObject
- {
- Q_OBJECT
- Q_PROPERTY(QString someattribute MEMBER m_someattribute)
- public slots:
- void jscallme()
- {
- QMessageBox::information(NULL,"jscallme","I'm called by js!");
- }
- void setsomeattribute(QString attr)
- {
- m_someattribute=attr;
- emit someattributeChanged(m_someattribute);
- }
- signals:
- void someattributeChanged(QString & attr);
- private:
- QString m_someattribute;
- };
- var updateattribute=function(text)
- {
- $("#attrid").val(text);
- }
- new QWebChannel(qt.webChannelTransport,
- function(channel){
- var webobj = channel.objects.webobj;
- window.foo = webobj;
- webobj.someattributeChanged.connect(updateattribute);
- });
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.
- class WebClass : public QObject
- {
- Q_OBJECT
- Q_PROPERTY(QString someattribute MEMBER m_someattribute NOTIFY someattributeChanged)
- public slots:
- void jscallme()
- {
- QMessageBox::information(NULL,"jscallme","I'm called by js!");
- }
- signals:
- void someattributeChanged(QString & attr);
- private:
- QString m_someattribute;
- };
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:
- 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:
- 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(转载)的更多相关文章
- javascript - C++, Qt, QtWebKit: How to create an html rendering window so that your application would get callbacks from JS calls? - Stack Overflow
javascript - C++, Qt, QtWebKit: How to create an html rendering window so that your application woul ...
- Qt WebEngine版本要求
WebEngine是Qt5.4之后加入的新特性,用Qt WebEngine取代之前的Qt Webkit http://wiki.qt.io/QtWebEngine windows版本 windows版 ...
- 解决 “Project ERROR: Unknown module(s) in QT: webengine”以及“Your MaintenanceTool appears to be older than 3.0.2. .” 的办法
1.环境 Windows10,Qt5.8.0 2.问题描述 需要使用到WebEngineView组件,在工程.pro中增加webengine后,Qt Creator应用程序输出中打印了 Project ...
- linux 下Qt WebEngine 程序打包简单记录
本次记录仅作参考. 程序说明: 程序是一个编解码器控制管理的工具,使用到的库有:Qt的WebEngine.OpenGL模块.poco库.libmicrohttpd.libcurl.libvlc.同时程 ...
- Qt WebEngine 网页交互
环境:Qt5.7.0,VS2013 一.简单介绍 从 Qt5.4 开始已经去掉 Qt WebKit 模块了,使用的是 chrome 内核封装的 QtWebEngine,浏览器相关的类有以下几个: QW ...
- Qt Unknown module(s) in QT: webengine
到今天位置好像Qt 出到了5.10还是5.9.x吧,本身是用MSVC 5.7.0本身就有支持 webengine这个模块 然后跟风升级了5.9.1,公司项目不用qt框架了用VC渣渣6.0.....然后 ...
- qt添加cef库嵌入web,linux 下Qt WebEngine 程序打包简单记录
http://www.cnblogs.com/oloroso/p/6051631.html http://www.cnblogs.com/oloroso/p/6149000.html
- 深入理解JavaScript的变量作用域(转载Rain Man之作)
在学习JavaScript的变量作用域之前,我们应当明确几点: JavaScript的变量作用域是基于其特有的作用域链的. JavaScript没有块级作用域. 函数中声明的变量在整个函数中都有定义. ...
- javascript keycode大全【转载】
keycode 8 = BackSpace BackSpace keycode 9 = Tab Tabkeycode 12 = Clearkeycode 13 = Enterkey ...
随机推荐
- 如何使用word发布blog
今天使用onenote的时候无意中点击了发布到博客选项,知道了word可以直接发布博客.但一直找不到选项所以google了一番,最终找到了.帮助连接 这里 这篇博客主要记录一下截图. 1. 通过one ...
- centos7配置外网
1设置网络连接中的NAT网络配置 2虚拟机的网络设置选择NAT连接设置如下,子网IP可通过ipconfig查看本地VMnet8,如我本地VMnet8 ip为:192.168.198.0 3 3.开启虚 ...
- Oracle 12C 物理Standby 主备切换switchover
Oracle 12C 物理Standby 主备切换switchover Oracle 12C 物理Standby 主备切换switchover Table of Contents 1. 简述 2. 切 ...
- 动态执行表不可访问,或在v$session
PLSQL Developer报“动态执行表不可访问,本会话的自动统计被禁止”的解决方案 PLSQL Developer报“动态执行表不可访问,本会话的自动统计被禁止”的解决方案 现象: 第一次用PL ...
- 从Windows系统到Linux系统转变的5大要点
当我在 Algoma (阿尔格玛)大学开始我现在的工作,一个图书系统管理员,我实在是对我的工作没有什么信心.尽管我在图书信息技术上有十年经验,对于我的第一个任务——协助开发和管理 Evergreen ...
- java:shiroProject
1.backend_system Maven Webapp: LoginController.java: package com.shiro.demo.controller; import org ...
- Ubuntu下借助URLOS实现快速安装DzzOffice企业办公套件
如今,越来越多的个人.团队甚至企业都在使用GSuite或者Office365等网络办公套件,为什么人们越来越喜爱使用网络办公套件?一方面是考虑数字资产的安全性以及管理效率,另一方面则是日益增大的协同办 ...
- Kali Linux 2019.2使用华为源
一.将默认的配置源注释掉 root@zinuo:~# vim /etc/apt/sources.list 注释: #deb http://http.kali.org/kali kali-rolling ...
- webdriervAPI(键盘事件)
from selenium import webdriver from selenium.webdriver.common.keys import Keys #导入键盘操作事件 driver ...
- s7-200日常使用烂笔头
这篇文章只是记录我的苦逼自控之路,有些是书上的,有些是自己发现的,不记载网上得出来的一些东西.只为强化记忆以及便于翻阅. 1.今天使用PC\PPI cable线缆连接成功了200,这个线是盗版线,之前 ...