本文介绍了如何告诉 QWebPage 不加载特定类型的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何告诉 QWebPage 不加载特定类型的资源,如 js、css 或 png?

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

推荐答案

解决方案是扩展 QNetworkAccessManager 类并覆盖它的虚方法 QNetworkAccessManager::createRequest 在我们的实现中,我们检查请求的 url 的路径,如果它是我们不想下载的,我们创建并移交一个空请求而不是真正的请求一.下面是一个完整的工作示例.

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"

这篇关于如何告诉 QWebPage 不加载特定类型的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-16 18:35