Capture server response with QWebEngineView

后端 未结 1 1574
广开言路
广开言路 2020-12-06 08:11

I\'m trying to create a Dialog in Qt which loads a URL (which I do not want to expose to the end-user, hence a Dialog). Once the user has entered their credentials on the pa

相关标签:
1条回答
  • 2020-12-06 08:30

    Since Qt 5.6 the proposed solution for what you are trying to achieve with QWebEngineView is QWebEngineUrlRequestInterceptor:

    Implementing the QWebEngineUrlRequestInterceptor interface and installing the interceptor on the profile enables intercepting, blocking, and modifying URL requests before they reach the networking stack of Chromium.

    It is an abstract class which means you need to subclass it to get what you want:

    #include <QWebEngineUrlRequestInterceptor>
    #include <QDebug>
    
    class RequestInterceptor : public QWebEngineUrlRequestInterceptor
    {
    public:
        explicit RequestInterceptor(QObject * parent = Q_NULLPTR) : QWebEngineUrlRequestInterceptor(parent) {}
        virtual void interceptRequest(QWebEngineUrlRequestInfo & info) Q_DECL_OVERRIDE;
    };
    
    void RequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo & info)
    {
        // Intercepting the requested URL
        QUrl url = info.requestUrl();
        qDebug() << "Request URL: " << url;
    
        // Optionally redirect the request URL but it only works for requests 
        // without payload data such as GET ones
        info.redirect(QUrl("https://www.google.com"));
    
        // Set HTTP header
        QByteArray httpHeaderName = "SomeHeaderName";
        QByteArray httpHeaderValue = "SomeHeaderValue";
        info.setHttpHeader(httpHeaderName, httpHeaderValue);
    }
    

    Then you need to register the pointer to this interceptor in QWebEngineProfile for a particular QWebEnginePage, like this:

    QWebEngineView * view = new QWebEngineView;
    RequestInterceptor * interceptor = new RequestInterceptor(view);
    QWebEngineProfile * profile = new QWebEngineProfile(view);
    profile->setRequestInterceptor(interceptor);
    QWebEnginePage * page = new QWebEnginePage(profile, view);
    view->setPage(page);
    
    0 讨论(0)
提交回复
热议问题