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);
ps:本博文只用于日常备注及学习交流,请勿用于任何商业用途,涉及网摘等资料如有侵犯原作者权利,请联系确保及时更正!