0

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.

Ram M
  • 1
  • 2
  • I think your best direction is some `js` postprocessing. You should be able to reload the `iframe` with `iframe.setAttribute('src', iframe.getAttribute('src'))` – Kamil.S Oct 02 '19 at 19:33
  • Thanks @Kamil.S. Could you elaborate further? I am not sure where I can the required headers in the above approach. – Ram M Oct 03 '19 at 10:05
  • Check https://stackoverflow.com/a/220169/5329717 – Kamil.S Oct 03 '19 at 11:30
  • Btw some minimalistic `html` file with at least one `iframe` ilustrating your problem would really help in this question. – Kamil.S Oct 03 '19 at 11:41

0 Answers0