WKWebView 拦截请求头,重新添加请求头信息
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"navigationAction = %@, \n request = %@", navigationAction, navigationAction.request.URL);
// 禁止图片类型 a标签超链接跳转
if ([[navigationAction.request.URL absoluteString] containsString:@".jpg"] ||
[[navigationAction.request.URL absoluteString] containsString:@".jpeg"] ||
[[navigationAction.request.URL absoluteString] containsString:@".png"] ||
[[navigationAction.request.URL absoluteString] containsString:@".gif"]) {
decisionHandler(WKNavigationActionPolicyCancel);
}
else if (navigationAction.navigationType == WKNavigationTypeBackForward){
[webView reload];
decisionHandler(WKNavigationActionPolicyAllow);
}
else{
// 拦截请求头,重新添加请求头信息
NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
NSDictionary *requestHeaders = navigationAction.request.allHTTPHeaderFields;
if ([requestHeaders isKindOfClass:[NSDictionary class]]) {
if (![requestHeaders objectForKey:@"device_id"] ) {
NSMutableURLRequest *request = [PublicWKWebViewServices setKeyValueForRequestHeader:[mutableRequest.URL absoluteString]];
[webView loadRequest:request];
decisionHandler(WKNavigationActionPolicyCancel);
return ;
}
}
decisionHandler(WKNavigationActionPolicyAllow);
}
}
参考:
https://www.jianshu.com/p/0183d978eb5c
https://www.jianshu.com/p/21b1f5a2e909
https://www.jianshu.com/p/b0ed73a61ac4
https://blog.csdn.net/yxl123546/article/details/72779017