I want to access QtObject from HTML-page running in WebView - invoke methods, read/write properties, etc.
As far as I understood, I need to establish WebSockets connection between QML and HTML sides, and then use it as a transport for WebChannel.
Don't confuse WebView with WebEngineView - I know how to do it with WebEngineView, but I need to do it with WebView.
So, here's what I have.
QML side
QtObject {
id: someObject
WebChannel.id: "backend"
property string someProperty: “property value"
}
WebSocketServer {
listen: true
port: 55222
onClientConnected: {
console.log(webSocket.status);
//webSocket.onTextMessageReceived.connect(function(message) {
// console.log(qsTr("Server received message: %1").arg(message));
//});
}
}
WebView {
url: "index.html"
//webChannel: channel // invalid property name "webChannel"
//experimental.webChannel.registeredObjects: [someObject] // invalid property name "experimental"
}
WebChannel {
id: channel
registeredObjects: [someObject]
}
HTML side
window.onload = function()
{
// here will be QtObject from QML side
var backend;
var socket = new WebSocket("ws://localhost:55222");
socket.onopen = function()
{
//socket.send("some message");
new QWebChannel(socket, function(channel) {
backend = channel.objects.backend;
});
};
}
function alertProperty()
{
alert(backend.someProperty);
}
Simple message exchange works fine (socket.send()
), so transport is okay, but how do I assign WebChannel to WebView? With WebEngineView it was simple, there is a webChannel
property there (and there is even no need in using WebSockets), but there is nothing alike in WebView. I mean, something has to tell WebView that WebChannel contains my QtObject so it would be visible to JS?
And if WebView does not support WebChannel(?), how to do it with external browser then? This example shows that it is possible with C++, but I want to do it with QML.
I use Qt 5.11.1.
WebView
does not supportWebChannel
by default. So the solution is to useWebSocketServer
withQWebChannelAbstractTransport
as I show below:main.cpp
main.qml
index.html
The complete example can be found in the following link