iOS网页wkwebview拦截请求,添加头文件
遇到一个需求:在网页抛出一切请求时,不管是资源请求还是重定向等,需要拦截掉并在header添加信息,ng拿到去做处理,访问不同资源服务器。
一开始想到的方式是:通过WKNavigationDelegate的代理方法- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
来在请求之前获得请求信息,并把请求头信息添加进去,如下:
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"灰度测试h5Url: %@",navigationAction.request.URL.absoluteString);
if ([navigationAction.request.URL.absoluteString containsString:OUR_URL_ID]) {
// 拦截所有网络请求头,重新添加参数请求头信息
NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
NSDictionary *requestHeaders = navigationAction.request.allHTTPHeaderFields;
if ([requestHeaders isKindOfClass:[NSDictionary class]]) {
//简单通过Version_Key判断下是否已经加入了请求信息
if ([AFNetWorkManager KeyUrlrequestOneNull:requestHeaders]) {
[AFNetWorkManager addWebDefaultKeyUrlrequest:mutableRequest];
[webView loadRequest:mutableRequest];
NSLog(@"灰度测试h5Url: %@ \n请求头:%@",navigationAction.request.URL.absoluteString,mutableRequest.allHTTPHeaderFields);
decisionHandler(WKNavigationActionPolicyCancel);
return ;
}else{
//参数正常,放开请求
NSLog(@"灰度测试h5Url: %@ \n请求头:%@",navigationAction.request.URL.absoluteString,requestHeaders);
decisionHandler(WKNavigationActionPolicyAllow);
}
}else{
//没有请求头,加上新的请求头,并赋予参数
mutableRequest.allHTTPHeaderFields = [NSMutableDictionary new];
[AFNetWorkManager addWebDefaultKeyUrlrequest:mutableRequest];
[webView loadRequest:mutableRequest];
NSLog(@"灰度测试h5Url: %@ \n请求头:%@",navigationAction.request.URL.absoluteString,mutableRequest.allHTTPHeaderFields);
decisionHandler(WKNavigationActionPolicyCancel);
}
}else{
//本地请求资源,pdf等
decisionHandler(WKNavigationActionPolicyAllow);
}
}
但是经过打印发现,只拦截了一些html请求,向png、css、js资源请求,并没有拦截到,甚至没有走这个方法。
无奈,只能网上搜索,结果发现了:https://github.com/fenglee594/WKWebViewRequestHook
这个demo,稍加改动,亲测有效。