How do I get all cookies from a WKWebView instance?
Here are what I've tried so far:
I tried using - [WKWebView evaluateJavaScript:completionHandler:]
to evaluate document.cookie
- unfortunately the result does not contain cookies that marked as HttpOnly.
According to Introducing the Modern WebKit API (WWDC 2014 Session 206), it should be possible to get an response
object from an instance of WKNavigation
. However, according to the class reference, WKNavigation
does not contain any public method / property.
Since this question hasn't been answered after one year, I am posting my imperfect, but working solution:
You can have access to an NSHTTPURLResponse
object in - webView:decidePolicyForNavigationResponse:decisionHandler:
method defined on WKNavigationDelegate
. You can later extract the cookies manually from the HTTP header:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
NSHTTPURLResponse* response = navigationResponse.response;
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@""]];
for (NSHTTPCookie *cookie in cookies) {
// Do something with the cookie
}
decisionHandler(WKNavigationResponsePolicyAllow);
}
Please post your solution if you have a better one.
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