How to use QWebEngineUrlRequestInterceptor

前端 未结 2 1873
时光说笑
时光说笑 2021-01-06 11:34

I need to intercept requests made in our WebEngine qml component in our Qt application.

I have found documentation on QWebEngineUrlRequestInterceptor which seems to

2条回答
  •  别那么骄傲
    2021-01-06 12:01

    The QWebEngineUrlRequestInterceptor class provides an abstract base class for URL interception, i recommend it to handle custom protocols, (mail://, example:// ....)

    Let's implement it by subclasing QWebEngineUrlRequestInterceptor:

    Your header file exampleurlschemehandler.h file:

    class ExampleUrlSchemeHandler : public QWebEngineUrlSchemeHandler
    {
        Q_OBJECT
    public:
        explicit ExampleUrlSchemeHandler(QObject *parent = 0);
    public:
    
        void requestStarted(QWebEngineUrlRequestJob *request);
    };
    

    Your cpp file:

    ExampleUrlSchemeHandler::ExampleUrlSchemeHandler(QObject *parent) : QWebEngineUrlSchemeHandler(parent){}
    
    void ExampleUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *request){
        // Abort the request if you want to redirect it or something
        request->fail(QWebEngineUrlRequestJob::RequestAborted);
        // Get the URL
        const QUrl url = request->requestUrl();
        // Do amazing thing with your URL
        // .....
    }
    

    Now install it in your default QWebEngineProfile:

    const QString EXAMPLE_SCHEMA_HANDLER = "example://" /* http://, https://, mail:// ....   */;
    const QWebEngineUrlSchemeHandler* installed =  QWebEngineProfile::defaultProfile()->urlSchemeHandler(EXAMPLE_SCHEMA_HANDLER);
            if (!installed)
                profile()->installUrlSchemeHandler(EXAMPLE_SCHEMA_HANDLER, new WebAppUrlSchemeHandler(this));
    

    Other method, to handle HTTP/HTTPS request is subclassing QWebEnginePage, and reimplementing acceptNavigationRequest():

    bool WebAppPage::acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool main) {
        // Example: We want to redirect all links clicked by user to native webbrowser
            if (type == QWebEnginePage::NavigationTypeLinkClicked)
                    QDesktopServices::openUrl(url);
    }
    

    Now, set this page in your QWebEngineView.

提交回复
热议问题