func webView(webView: WKWebView!, decidePolicyForNavigationAction navigationAction: WKNavigationAction!, decisionHandler: ((WKNavigationActionPolicy) -> Void)!) { var request = NSMutableURLRequest(URL: navigationAction.request.URL) request.setValue("value", forHTTPHeaderField: "key") decisionHandler(.Allow) }
In the above code I want to add a header to the request. I have tried to do navigationAction.request.setValue("IOS", forKey: "DEVICE_APP")
but it doesn't work.
please help me in any way.
AFAIK sadly you cannot do this with WKWebView
.
It most certainly does not work in webView:decidePolicyForNavigationAction:decisionHandler:
because the navigationAction.request
is read-only and a non-mutable NSURLRequest
instance that you cannot change.
If I understand correctly, WKWebView
runs sandboxed in a separate content and network process and, at least on iOS, there is no way to intercept or change it's network requests.
You can do this if you step back to UIWebView
.
There are many different ways to do that, I found that the easiest solution was to subclass WKWebView and override the loadRequest method. Something like this:
class CustomWebView: WKWebView { override func load(_ request: URLRequest) -> WKNavigation? { guard let mutableRequest: NSMutableURLRequest = request as? NSMutableURLRequest else { return super.load(request) } mutableRequest.setValue("custom value", forHTTPHeaderField: "custom field") return super.load(mutableRequest as URLRequest) } }
Then simply use the CustomWebView class as if it was a WKWebView.
EDIT NOTE: This will only work on the first request as pointed out by @Stefan Arentz.
NOTE: Some fields cannot be overridden and will not be changed. I haven't done a thorough testing but I know that the User-Agent
field cannot be overridden unless you do a specific hack (check here for an answer to that)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With