QtWebEngine - 同步执行JavaScript以读取函数结果

zup*_*zt3 10 c++ qt multithreading callback qtwebengine

我在我的一个C++类中使用以下方法(使用QtWebEngine):

    QString get()
    {
        QString result;

        view->page()->runJavaScript("test();", [this](const QVariant &v)
            {
                result = v.toString();
            });

        return result;
    }
Run Code Online (Sandbox Code Playgroud)

它是执行test()JS函数并返回此调用的结果.

不幸的是,回调是异步的,程序崩溃了.我怎样才能使它工作?

Dmi*_*try 6

回调是异步的,因为JavaScript执行不仅发生在另一个线程中,而且发生在另一个进程中.所以没有办法让它完全同步.

最好的解决方案是将C++代码迁移到异步工作.如果你不能这样做,唯一可行的解​​决方案是使用QEventLoop,有点像这样:

void ranJavaScript()
{
    emit notifyRanJavaScript();
}

QString get()
{
    QString result;
    QEventLoop loop;
    QObject::connect(this, SIGNAL(notifyRanJavaScript()), &loop, SLOT(quit()));
    view->page()->runJavaScript("test();", [this](const QVariant &v)
        {
            result = v.toString();
            this.ranJavaScript();
        });

    loop.exec();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

但请注意,此示例对于实际使用而言过于简单:您需要确保在启动事件循环之前未运行JavaScript.最合适的方法是实现一个正确的槽而不是lambda +将调用分解view->page()->runJavaScript()为另一个槽,该槽将启动事件循环异步调用.这个看似简单的任务有很多胶水代码,但这就是它需要的东西.这是一个例子:

MainWindow.h

#ifndef TMP_MAIN_WINDOW_H
#define TMP_MAIN_WINDOW_H

#include <QMainWindow>
#include <QVariant>

class QWebEngineView;
class QPushButton;

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget * parent = 0);

    QString get();

    void onScriptEnded(const QVariant & data);

Q_SIGNALS:
    void notifyRanJavaScript();

private Q_SLOTS:
    void onButtonPressed();

    void startScript();

private:
    QWebEngineView *    m_view;
    QPushButton *       m_button;
    QString             m_scriptResult;
};

#endif // TMP_MAIN_WINDOW_H
Run Code Online (Sandbox Code Playgroud)

MainWindow.cpp

#include "MainWindow.h"
#include <QWebEngineView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QEventLoop>
#include <QDebug>
#include <QTimer>

MainWindow::MainWindow(QWidget * parent) :
    QMainWindow(parent)
{
    m_view = new QWebEngineView;
    QWebEnginePage * page = new QWebEnginePage(m_view);
    m_view->setPage(page);

    QString html = QStringLiteral("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""
                                  "\"http://www.w3.org/TR/html4/strict.dtd\"><html>"
                                  "<head><h3>head</h3>\n</head>"
                                  "<script type=\"text/javascript\">function test() { return \"A!\"; }</script>"
                                  "<body>text\n</body></html>");
    m_view->page()->setHtml(html);

    m_button = new QPushButton;
    m_button->setMinimumWidth(35);
    m_button->setText(QStringLiteral("Test"));
    QObject::connect(m_button, SIGNAL(pressed()), this, SLOT(onButtonPressed()));

    QHBoxLayout * buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(m_button);
    buttonLayout->addStretch();

    QVBoxLayout * viewLayout = new QVBoxLayout;
    viewLayout->addLayout(buttonLayout);
    viewLayout->addWidget(m_view);

    QWidget * widget = new QWidget(this);
    widget->setLayout(viewLayout);

    setCentralWidget(widget);
}

QString MainWindow::get()
{
    QEventLoop loop;
    QObject::connect(this, SIGNAL(notifyRanJavaScript()), &loop, SLOT(quit()));

    // Schedule the slot to run in 0 seconds but not right now
    QTimer::singleShot(0, this, SLOT(startScript()));

    // The event loop would block until onScriptEnded slot is executed
    loop.exec();

    // If we got here, the script has been executed and the result was saved in m_scriptResult
    return m_scriptResult;
}

void MainWindow::onScriptEnded(const QVariant & data)
{
    qDebug() << QStringLiteral("Script ended: ") << data;
    m_scriptResult = data.toString();
    emit notifyRanJavaScript();
}

void MainWindow::onButtonPressed()
{
    QString str = get();
    QMessageBox::information(this, QStringLiteral("Script result"), str,
                             QMessageBox::StandardButton::Ok);
}

struct Functor
{
    Functor(MainWindow & window) : m_window(window) {}
    void operator()(const QVariant & data)
    {
        m_window.onScriptEnded(data);
    }
    MainWindow & m_window;
};

void MainWindow::startScript()
{
    qDebug() << QStringLiteral("Start script");
    m_view->page()->runJavaScript(QStringLiteral("test();"), Functor(*this));
}
Run Code Online (Sandbox Code Playgroud)

  • 我没有说回调是在不同的进程中执行的.我说**JavaScript**代码(它是`runJavaScript`的参数)在一个名为`QWebEngineProcess`的不同进程中执行(实际上是JIT编译和执行). (2认同)