How to intercept request from QWebEngineView and serving them directely from the application?

805 Views Asked by At

Is there a way with QWebEngineView to intercept an http request, and to serve it server-less from the app ?

I heard about QWebEngineUrlRequestInterceptor and acceptNavigationRequest(), but they provide only inspection on requests, and redirection for get... But I would like to make the http response from the Qt app.

(I added pyqt in the tags because I would use it from python, but a c++ answer is acceptable too)

1

There are 1 best solutions below

0
Sam vL On

The qt documentation says the redirection is only for GET request. However, when trying it out (PyQt6==6.4.0) we found out that this is actually not true. If you redirect a POST request in the WebEngine to a local webserver listening on localhost, you will actually receive the request including the payload.

Perhaps this is because Webkit doesn't include the payload for redirect and Chromium does? (I couldn't find docs stating the difference.)

from PyQt6.QtCore import QUrl
from PyQt6.QtWebEngineCore import QWebEngineUrlRequestInterceptor


class WebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor):
    def interceptRequest(self, info):
        method = info.requestMethod()
        if method == "POST":
            if info.requestUrl().url() == "https://my-url-to-something":
                info.redirect(QUrl("http://127.0.0.1:8000"))