I have a web page loaded in a QWebView. In there, I would like to have JavaScript call a function of my application. That function would then returns some strings that JavaScript would dynamically display.
Can it be done using QWebView? Basically, is it possible to have some bridge between the application (in C++) and the QWebView control?
This is how I ended up doing it. I declared a "JavaScriptBridge" class in my header file with a
Q_INVOKABLE
method.Q_INVOKABLE
methods can be called from JavaScript:Then in my .cpp file, I create the bridge:
And I listen to the
javaScriptWindowObjectCleared
signal. This step is important because WebKit is going to clear all the JavaScript objects when loading a new page, so you need to add back the bridge every time:Finally, in the
javaScriptWindowObjectCleared
slot, I add the JavaScript bridge:Now from JavaScript, there will be a global "ehbridge" object exposed. I can call its methods like a normal JavaScript object (Qt converts Qt's types to JavaScript types)