简体   繁体   中英

QWebEngineView request body interception

A user using QWebEngineView in my application fills some form. This form uses post method to submit data to server. How can I get params from user's body request?

I've found such thing as QWebEngineUrlRequestInterceptor , but it works only for urls.

You can use QWebEnginePage::acceptNavigationRequest .

Whenever a form is submitted, you can get the contents of input by using JavaScript and then accept the request to proceed as usual.

Like Anmol Gautam said, you need to reimplement QWebEnginePage::acceptNavigationRequest function and get needed data using JavaScript.

Here is an example how to do it:

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;
}

use QWebEngineView::setPage to set your WebPage subclass to WebView before you call WebViews load function.

Here is a link for more info about HTML DOM forms Collection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM