I want to inject custom headers into NSURLRequests
made for top-level frames of WKWebView
and all of its iFrames.
To achieve this I am listening to the
- webView:decidePolicyForNavigationAction:decisionHandler:
method. In this method i want to cancel the existing page load and create a new NSURLRequest
and reload the page.
Here's the code snippet I am using,
- (void)webView:(WKWebView*)webView
decidePolicyForNavigationAction:(WKNavigationAction*)action
decisionHandler:
(void (^)(WKNavigationActionPolicy))decisionHandler {
NSString* header = @"Custom-Header";
if([action.request.allHTTPHeaderFields objectForKey:header] ){
NSLog(@"Header already added for URL - %@",action.request.URL.absoluteString );
}
else{
decisionHandler(WKNavigationActionPolicyCancel);
NSLog(@"Adding header for URL %@",action.request.URL.absoluteString);
NSMutableURLRequest *mutableRequest = [action.request mutableCopy];
NSString* headerVal;
if(action.targetFrame.mainFrame)
{
headerVal = @"MAINFRAME";
}
else
{
headerVal = @"SUBFRAME";
}
[mutableRequest addValue:headerVal forHTTPHeaderField:header];
[action.targetFrame.webView loadRequest:mutableRequest];
return;
}
// further processing
}
However with this approach I face the following problem - If the callback is received for a iFrame, the entire page reloads with the iFrame URL. Instead I want only the iFrame to reload with the URL. Is there any way to solve this?
Note that at the end of this I want to be able to send a custom header indicating whether the request originated from the main frame or an iFrame.Please do suggest if there are better solutions to achieve this.