javascriptqtcallbackqwebenginepage

Calling Qt slot from JavaScript


I'm using a QWebEnginePage class for rendering my webpage. And i need to implement callback function. So first i want to register my slot in JS and call this slot from JS when it needed (for example, after click button on the webpage). I tried to do like there, but it not that i need, because it illustrate only calling JS function from Qt and recieving the result, but i need callback. Is it possible to implement?

in earlier versions of Qt there was a module qtwebkit and my goal could be achieved like discribed there using addToJavaScriptWindowObject method. But how to do that with qtwebenginewidgets module which doesn't have that and even similar method?


Solution

  • In QWebEngine you can use QWebChannel in order to communicate with your JS

    Create a proxy object to communicate with Qt from JS

    // This Object will be registered in the web channel
    class MyJSObj : public QObject
    {
     Q_OBJECT
    public:
       MyJSObj(QObject * poParent = Q_NULLPTR);
    
       Q_INVOKABLE int foo(); // call from JS
    };
    

    In your cpp code

    // Create proxy object
    m_poMyJSObj = new MyJSObj(this);
    
    // Create channel
    m_poWebView = new QWebEngineView(this);
    QWebChannel * poChannel = new QWebChannel();
    m_poWebView->page()->setWebChannel(poChannel);
    
    // Register your proxy object
    const QString oJSObjectName = "mJSQtObject"; // use in JS to call Qt functions
    poChannel->registerObject(oJSObjectName, m_poMyJSObj);
    

    In JS

    new QWebChannel(qt.webChannelTransport, function (channel) {
                // now you retrieve your object
                var JSQtObject = channel.objects.mJSQtObject;
                // call Qt function from JS
                var qtValue = JSQtObject.foo();
            });
    

    Please note that you will have to include the qwebchannel.js on the HTML side