QWebEngineView请求体拦截

QWebEngineView request body interception

在我的应用程序中使用 QWebEngineView 的用户填写了一些表格。此表单使用 post 方法向服务器提交数据。如何从用户的正文请求中获取参数?

我找到了 QWebEngineUrlRequestInterceptor 这样的东西,但它只适用于 url。

您可以使用 QWebEnginePage::acceptNavigationRequest

每当提交表单时,您可以使用JavaScript获取输入的内容,然后接受请求以照常进行。

喜欢Anmol Gautam said, you need to reimplement QWebEnginePage::acceptNavigationRequest函数并使用JavaScript获取所需数据。

这是一个如何操作的例子:

mywebpage.h

#include <QWebEnginePage>

class MyWebPage : public QWebEnginePage
{
    Q_OBJECT
public:
    explicit MyWebPage(QWebEngineProfile *profile = Q_NULLPTR, QObject *parent = Q_NULLPTR);

protected:
    bool acceptNavigationRequest(const QUrl & url, QWebEnginePage::NavigationType type, bool isMainFrame);
}

mywebpage.cpp

MyWebPage::MyWebPage(QWebEngineProfile *profile, QObject *parent):QWebEnginePage(profile, parent),
{
//...
}

bool MyWebPage::acceptNavigationRequest(const QUrl & url, QWebEnginePage::NavigationType type, bool isMainFrame)
{
    if(type == QWebEnginePage::NavigationTypeFormSubmitted)
    {
        qDebug() << "[FORMS] Submitted" <<  url.toString();
        QString jsform = "function getformsvals()"
                         "{var result;"
                          "for(var i = 0; i < document.forms.length; i++){"
                         "for(var x = 0; x < document.forms[i].length; x++){"
                         "result += document.forms[i].elements[x].name + \" = \" +document.forms[i].elements[x].value;"
                         "}}"
                         "return result;} getformsvals();";

        this->runJavaScript(jsform, [](const QVariant &result){ qDebug() << "[FORMS] found: " << result; });
    }
    return true;
}

在调用 WebViews 加载函数之前,使用 QWebEngineView::setPage 将 WebPage 子类设置为 WebView。

这里有一个 link 有关 HTML DOM forms Collection

的更多信息