Alternative of addToJavaScriptWindowObject in Qt 5.12.4
-
I am trying to migrate my code from QWebView to QWebEngine. I want to add an object from my code into the javascript. In QWebView it was possible with the function addToJavaScriptWindowObject. How can we do this in QWebEngine.
webview->page()->mainFrame()->addToJavaScriptWindowObject("qtObject", this);
Our java script need to call functions of "qtObject".
-
@Hetal Hi,
According to this post on stackoverflow, It seems you need to use QWebChannel with QWebView.
Here is some link with more informations:
Qt WebChannel – bridging the gap between C++/QML and the web
Interacting with HTML from QML over WebChannel/WebSockets
QTDD14 - QtWebChannel - Bridging the Gap between HTML and Qt - Milian Wolff, KDAB -
@Gojir4 Thanks a lot, Our Qt application is already using QWebSocket, can we use the same QWebSocket for establishing the Web Channel, as per our understanding QWebSocket is heavy object.
We have referred the "Qt WebChannel Standalone Example". Also, please note that we do not require to send messages to server using QWebChannel. We only want, method of "qtObject"' gets called from server's java script code
.
So the question is whether QWebSocketServer is required to have QWebChannel to work?
or Only QWebChannel and QWebChannelAbstractTransport are required to be implemented.Please suggest.
-
@Hetal Hi, you may find the previous post below useful to your problem:
https://forum.qt.io/topic/70968/qwebchannel-js-uncaught-referenceerror-qt-is-not-defined
This previous post assumed that you have no control over the js code that will run in your QWebEngine.
If you do have the control over the js code, you may simply register your C++ obj using
//your C++ code here QWebChannel* pWebChannel = new QWebChannel(this); pWebChannel ->registerObject(nameOfC++Obj, pC++Obj); QWebEnginePage *pWebPage = new QWebEnginePage(pWebProfile); pWebPage->setWebChannel(pWebChannel );
add the following part to your js code:
//your js code here <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script> if (typeof qt != 'undefined') { new QWebChannel(qt.webChannelTransport, function(channel) { if (typeof channel.objects != 'undefined') { YouJsObj = channel.objects.YourC++Obj; } }); }