Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...