Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cookies from WKWebView?

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.

like image 834
Siyu Song Avatar asked Jan 30 '15 09:01

Siyu Song


1 Answers

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.

like image 119
Siyu Song Avatar answered Sep 28 '22 21:09

Siyu Song