Question

How to tell QWebPage not to load specific type of resources like js, css or png?

Was it helpful?

Solution

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"

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top