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 : //Top level page
strInfo = "ResourceTypeMainFrame";
break; case : //Frame
strInfo = "ResourceTypeSubFrame";
break; case : //CSS stylesheet
strInfo = "ResourceTypeStylesheet";
break; case : //External script
strInfo = "ResourceTypeScript";
break; case : //Image
strInfo = "ResourceTypeImage";
break; case : //Font
strInfo = "ResourceTypeFontResource";
break; case : //Sub-resource
strInfo = "ResourceTypeSubResource";
break; case : //Plugin object
strInfo = "ResourceTypeObject";
break; case : //Media resource
strInfo = "ResourceTypeMedia";
break; case : //Resource of dedicated worker
strInfo = "ResourceTypeWorker";
break; case : //Resource of shared worker
strInfo = "ResourceTypeSharedWorker";
break; case : //Explicitly requested prefetch
strInfo = "ResourceTypePrefetch";
break; case : //Favicon
strInfo = "ResourceTypeFavicon";
break; case : //XML http request
strInfo = "ResourceTypeXhr";
break; case : //Ping request
strInfo = "ResourceTypePing";
break; case : //Resource of service worker
strInfo = "ResourceTypeServiceWorker";
break; case : //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);