Denis Popov
Denis Popov

Reputation: 57

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.

Upvotes: 1

Views: 1071

Answers (2)

Xplatforms
Xplatforms

Reputation: 2232

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

Upvotes: 1

Anmol Gautam
Anmol Gautam

Reputation: 1020

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.

Upvotes: 2

Related Questions