How to inject QWebChannel.js before the page loads



  • The following pages need to communicate with C ++ the first time, how to inject QWebChannel.js

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
    <script type="text/javascript">
    window.invoke("testInvoke", "testCallback");
    </script>
    </body>
    </html>

    Implementation code is as follows:

    QFile webChannelFile(":/qtwebchannel/qwebchannel.js");
    if (!webChannelFile.open(QIODevice::ReadOnly))
    {
        qDebug()<<QString("Couldn't open qwebchannel.js file: %1").arg(webChannelFile.errorString());
        return Q_NULLPTR;
    }
    QByteArray webChannelJs = webChannelFile.readAll();
    webChannelJs.append(
             "\n"
             "new QWebChannel(qt.webChannelTransport, function(channel) {"
             "     window.invoke = channel.objects.workObject; "
             "});");
    
    QWebEngineScript script;
        script.setSourceCode(webChannelJs);
        script.setName("qwebchannel.js");
        script.setWorldId(QWebEngineScript::MainWorld);
        script.setInjectionPoint(QWebEngineScript::DocumentCreation);
        script.setRunsOnSubFrames(false);
        profile->scripts()->insert(script);
    

    Execution error window.invoke is not a function
    How to do.



  • I have already solved it.


  • Qt Champions 2017

    @elliyu said in How to inject QWebChannel.js before the page loads:

    I have already solved it.

    Then please mark this thread as solved now.

    By the way, it would be nice for the others if you could share how you solved it.

    Merry Christmas.



  • Re: How to inject QWebChannel.js before the page loads

      QByteArray ccJSFunc = "function invokeQT(funcName, params, funcID) { \n"
                          "try{\n"
                          "qt.webChannelTransport.send(JSON.stringify({\n"
                          "type:6,\n"
                          "object:'ctInvoke',\n"
                          "id:6,\n"
                          "method:6,\n"
                          "args:[funcName, params, funcID]\n"
                          "}))\n"
                          "}catch(e){console.warn('invokeQT call failed', e)}\n}\n"
                          "window.external = window.external || {}\n"
                          "window.external.invoke = window.external.invoke || invokeQT\n";
      QWebEngineScript scriptCC;
      scriptCC.setSourceCode(ccJSFunc);
    scriptCC.setWorldId(QWebEngineScript::MainWorld);
    scriptCC.setName("cccustom.js");
    scriptCC.setInjectionPoint(QWebEngineScript::DocumentCreation);
    scriptCC.setRunsOnSubFrames(true);
    

    The same way qwebchannel.js, js can be inserted above this.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.