1、js往Qt中发送消息
1.1、Qt中注册对象
auto pWebView = new QWebEngineView(this);
auto pWebPage = new QWebEnginePage(this);
auto jsProtocol = new MyObject(this);
auto pWebChannel = new QWebChannel(this);
pWebChannel->registerObject("myProjectInterface", jsProtocol);
pWebPage->setWebChannel(pWebChannel);
pWebView->setPage(pWebPage);
1.2、js中获取注册的对象
new QWebChannel(qt.webChannelTransport, function(channel){
this.qtContext = channel.objects.myProjectInterface;
});
2、Qt往js中发送消息
QWebEnginePage::runJavaScript("recvMessageFromQt('hello js, i am qt')")
//********************************************************
/// @brief
/// @author y974183789@gmail.com
/// @date 2022/12/2
/// @note
/// @version 1.0.0
//********************************************************
#include "MyProjectWebView.h"
#include <QWebEngineProfile>
#include <QWebChannel>
#include <QTimer>
#include <QDebug>
class MyObject : public QObject {
Q_OBJECT
public:
MyObject(QObject* parent)
: QObject(parent){}
~MyObject(){}
public Q_SLOTS:
void doMessage(const QString& msg){
//TODO 处理js发送过来的消息
qDebug() << msg;
}
};
MyProjectWebView::MyProjectWebView(QWidget* parent)
: QWebEngineView(parent) {
auto jsProtocol = new MyObject(this);
QWebEnginePage *pWebPage = new QWebEnginePage(this);
setPage(pWebPage);
QWebChannel *pWebChannel = new QWebChannel(this);
pWebChannel->registerObject("myProjectInterface", jsProtocol);
pWebPage->setWebChannel(pWebChannel);
QTimer::singleShot(5000, this, [pWebPage](){
//发送消息到js
pWebPage->runJavaScript(QString("recvMessageFromQt('%1');").arg("hello js, i am a Qter"));
});
setContextMenuPolicy(Qt::NoContextMenu);
}
MyProjectWebView::~MyProjectWebView() {
}
<!doctype html>
<html>
<head>
<title>Web Notifications Example</title>
<script type="text/javascript" src="qwebchannel.js"></script>
<script>
this.qtContext = undefined
//init QtWebChannel
new QWebChannel(qt.webChannelTransport, function(channel){
this.qtContext = channel.objects.myProjectInterface;
});
function sendMessageToQt(msg) {
//send message to qt Application
if(typeof this.qtContext != 'undefined') {
this.qtContext.doMessage(msg);
}
}
function recvMessageFromQt(msg) {
alert("recvMessageFromQt" + msg);
}
function onMakeNotification() {
sendMessageToQt("hello Qter, i'am js");
}
</script>
</head>
<body style='text-align:center;'>
<h3>Click the button to send a notification</h3>
<button onclick='onMakeNotification()'>Notify!</button>
<p>
<output id='act'></output>
<button id='close' style='display: none;' onclick='closeNotification()'>Close</button>
</p><br>
<p>
<label for='state'>Permission:</label>
<output id='state'></output>
</p><br>
<h4>More info can be found on:</h4>
<ul style='list-style-type: none;'>
<li>W3 <a href='https://www.w3.org/TR/notifications'>Web Notifications</a> standard</li>
<li>Documentation for <a href='https://doc.qt.io'>Qt WebEngine</a> module</li>
</ul>
</body>
</html>