How to tell QWebPage not to load specific type of resources?

五迷三道 提交于 2019-11-27 11:03:38

The solution is to extend QNetworkAccessManager class and override it's virtual method QNetworkAccessManager::createRequest In our implementation we check the path of the requested url and if it's the one we don't want to download we create and hand over an empty request instead of the real one. Below is a complete, working example.

#include <QApplication>
#include <QUrl>

#include <QtWebKit/QWebPage>
#include <QtWebKit/QWebFrame>

#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QDebug>


class NAM : public QNetworkAccessManager {

    Q_OBJECT

protected:

    virtual QNetworkReply * createRequest(Operation op,
                                          const QNetworkRequest & req,
                                          QIODevice * outgoingData = 0) {

        if (req.url().path().endsWith("css")) {
            qDebug() << "skipping " << req.url();
            return QNetworkAccessManager::createRequest(QNetworkAccessManager::GetOperation,
                                                        QNetworkRequest(QUrl()));
        } else {
            return QNetworkAccessManager::createRequest(op, req, outgoingData);
        }
    }
};


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWebPage page;
    NAM nam;

    page.setNetworkAccessManager(&nam);
    page.mainFrame()->load(QUrl("http://google.com"));

    app.exec();
}

#include "main.moc"

I am actually struggling with the same problem, Piotr solution is assuming urls with file extensions, unfortunately this is not always the case.

it is possible toe get mime-type but only after we get the response' and this is offcore to late.

we tried to get the element context requesting the resources, say if it is an <img> element or <link> to get CSS, but req.originatingObject() only gives us a QWebFrame. i know for example that this was possible in mozilla code.

BTW, turning off javascript and auto load images will prevent loading of images and scripts.

If your goal is to prevent the Webpage from changing, you can take a look at

virtual bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type);

in QWebPage. You can inspect the request and return false if you want to prevent the request from being sent.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!