Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QWebEngineView. How to pass variable to Js function?



  • Hello. I would to know how I can pass a QString variable to js function. Example:

    QString value;
    webview = new QWebEngineView;
    webview->page()->runJavaScript("getInfo(value);");
    

    I receive this error:

    js: Uncaught ReferenceError: value is not defined
    [17240:14380:1213/204829.811:INFO:CONSOLE(1)] "Uncaught ReferenceError: value is not defined", source: qrc:/new/web/Posts.html (1)
    

    It only accepts if value is quoted, "value".
    Thanks



  • @Ucn_

    webview->page()->runJavaScript("getInfo('" + value1 + "', '" + value2  + "');");
    


  • @Ucn_
    To pass the value of value into your JavaScript, as shown, you'll want something like

    webview->page()->runJavaScript("getInfo('" + value + "');");
    

    Note how it is being quoted inside ' and '.

    There will be some alternative QString way of making the string I do with + above, if you prefer.



  • @JonB Thanks, can that method pass two parameters?



  • @Ucn_

    webview->page()->runJavaScript("getInfo('" + value1 + "', '" + value2  + "');");
    


  • @JonB Thanks.



  • @Ucn_
    OK, I believe this is how you do it in nice, readable fashion:

    webview->page()->runJavaScript(QString("getInfo('%1', '%2');").arg(value1).arg(value2));
    

    Looks neater, doesn't it? :)

    To do it properly/robustly, if your values could ever contain a ' character you would have to process your value via a function to protect embedded 's. Also if it has any \s.


Log in to reply