Search code examples
qtqtwebengine

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".


Solution

  • QFile webChannelJsFile(":/qtwebchannel/qwebchannel.js");
        if (!webChannelJsFile.open(QIODevice::ReadOnly)) {
            qDebug() << QString("Couldn't open qwebchannel.js file: %1").arg(webChannelJsFile.errorString());
        }
        else {
            qDebug() << "OK webEngineProfile";
            QByteArray webChannelJs = webChannelJsFile.readAll();
            webChannelJs.append(
                "\n"
                "var qtObject"
                "\n"
                "new QWebChannel(qt.webChannelTransport, function(channel) {"
                "     qtObject = channel.objects.qtObject;"
                "});"
            );
    
            QWebEngineScript script;
            script.setName("qwebchannel.js");
            script.setInjectionPoint(QWebEngineScript::DocumentCreation);
            script.setRunsOnSubFrames(false);
            script.setWorldId(QWebEngineScript::MainWorld);
            script.setSourceCode(webChannelJs);
    
            page->scripts().insert(script);
    
        QWebChannel *channel = new QWebChannel(page);
        channel->registerObject("qtObject", this);
        page->setWebChannel(channel);
        return page;