QWebEngineView拦截Url请求设置

QWebEngineView拦截Url请求设置

QWebEngineUrlRequestInterceptor类提供了一个拦截URL请求抽象基类,可通过实现QWebEngineUrlRequestInterceptor::interceptRequest接口拦截并修改相应的UIL请求,以达到相应需求效果,比如设置“Accept-Language”。

头文件定义

class TWebEngineUrlRequestInterceptor : public QWebEngineUrlRequestInterceptor
{
    Q_OBJECT

public:
    TWebEngineUrlRequestInterceptor(QObject *parent = Q_NULLPTR);
    void interceptRequest(QWebEngineUrlRequestInfo &info);
};

拦截接口实现

TWebEngineUrlRequestInterceptor::TWebEngineUrlRequestInterceptor(QObject *parent)
    : QWebEngineUrlRequestInterceptor(parent)
{
}

void TWebEngineUrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &info)
{
    QString strInfo = "";
    switch (info.resourceType())
    {
    case 0:  //Top level page
        strInfo = "ResourceTypeMainFrame"; 
        break;

    case 1:  //Frame
        strInfo = "ResourceTypeSubFrame";
        break;

    case 2:  //CSS stylesheet
        strInfo = "ResourceTypeStylesheet";
        break;

    case 3:  //External script
        strInfo = "ResourceTypeScript";
        break;

    case 4:  //Image
        strInfo = "ResourceTypeImage";
        break;

    case 5:  //Font
        strInfo = "ResourceTypeFontResource";
        break;

    case 6:  //Sub-resource
        strInfo = "ResourceTypeSubResource";
        break;

    case 7:  //Plugin object
        strInfo = "ResourceTypeObject";
        break;

    case 8:  //Media resource
        strInfo = "ResourceTypeMedia";
        break;

    case 9:  //Resource of dedicated worker
        strInfo = "ResourceTypeWorker";
        break;

    case 10:  //Resource of shared worker
        strInfo = "ResourceTypeSharedWorker";
        break;

    case 11:  //Explicitly requested prefetch
        strInfo = "ResourceTypePrefetch";
        break;

    case 12:  //Favicon
        strInfo = "ResourceTypeFavicon";
        break;

    case 13: //XML http request
        strInfo = "ResourceTypeXhr";
        break;

    case 14: //Ping request
        strInfo = "ResourceTypePing";
        break;

    case 15: //Resource of service worker
        strInfo = "ResourceTypeServiceWorker";
        break;

    case 16: //Unknown resource
        strInfo = "ResourceTypeUnknown";
        break;

    default: 
        strInfo = "Unknown type"; 
        break;
    }

    qDebug() << "RequestMethod===" << info.requestMethod() << "\n"
        << "RequestUrl===" << info.requestUrl() << "\n"
        << "RequestType===" << strInfo;
    
    //Set the value of the Accept-Language HTTP request-header.
    info.setHttpHeader("Accept-Language", "zh-CN");
}

接口调用,通过设置默认QWebEngineProfile属性

TWebEngineUrlRequestInterceptor *webInterceptor = new TWebEngineUrlRequestInterceptor();
QWebEngineProfile::defaultProfile()->setRequestInterceptor(webInterceptor);
posted @ 2017-03-15 10:13  sz_leez  阅读(6949)  评论(0编辑  收藏  举报