From f8d646db40c103c7e8c4bc773cda3e55b96e2e47 Mon Sep 17 00:00:00 2001 From: ShaopengLin Date: Thu, 30 May 2024 16:59:31 -0400 Subject: [PATCH] Disables external resource fetching Webpages blocks all requests with Url not starting with "zim://", i.e. native to the Zim file. --- src/kprofile.cpp | 15 +++++++++++++++ src/kprofile.h | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/kprofile.cpp b/src/kprofile.cpp index 052e441..fa09dc5 100644 --- a/src/kprofile.cpp +++ b/src/kprofile.cpp @@ -11,6 +11,11 @@ KProfile::KProfile(QObject *parent) : connect(this, &QWebEngineProfile::downloadRequested, this, &KProfile::startDownload); installUrlSchemeHandler("zim", &m_schemeHandler); settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true); +#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) // Earlier than Qt 5.13 + setRequestInterceptor(new ExternalReqInterceptor(this)); +#else // Qt 5.13 and later + setUrlRequestInterceptor(new ExternalReqInterceptor(this)); +#endif } #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) @@ -48,3 +53,13 @@ void KProfile::downloadFinished() msgBox.setText(gt("download-finished-message")); msgBox.exec(); } + +void ExternalReqInterceptor::interceptRequest(QWebEngineUrlRequestInfo &info) +{ + const QString reqUrl = info.requestUrl().toString(); + if (!reqUrl.startsWith("zim://")) + { + qDebug() << "Blocked external request to URL: " << reqUrl; + info.block(true); + } +} diff --git a/src/kprofile.h b/src/kprofile.h index 59c793f..98e75a9 100644 --- a/src/kprofile.h +++ b/src/kprofile.h @@ -2,6 +2,7 @@ #define KPROFILE_H #include +#include #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include #else @@ -30,4 +31,21 @@ public slots: void downloadFinished(); }; +/** + * @brief Intercepts and blocks a request if it is not native to our zim file. + * https://stackoverflow.com/questions/70721311/qwebview-disable-external-resources + */ +class ExternalReqInterceptor : public QWebEngineUrlRequestInterceptor +{ + Q_OBJECT +public: + explicit ExternalReqInterceptor(QObject *parent = nullptr) + : QWebEngineUrlRequestInterceptor(parent) + { + } + +protected: + void interceptRequest(QWebEngineUrlRequestInfo &info) override; +}; + #endif // KPROFILE_H