How to get all cookies from WKWebView

I did some research, and I was able to get some cookies from the grabbing it from NSHTTPURLResponse object. this, however, does not contain all the cookies used by WKWebView.


- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler

{

NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;

NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];


for (NSHTTPCookie *cookie in cookies) {

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

decisionHandler(WKNavigationResponsePolicyAllow);

}


I tried get cookies with

WKUserScript
like :

http://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview

but not get all cookies, please support for me.

Thanks,

Replies

How to get all cookies from WKWebView

There isn’t a solution that works in all cases, alas. All the approaches I know of have issues:

  • NSHTTPCookieStorage isn’t reliable because WKWebView does all of its networking in a separate process, so you can’t get at the NSHTTPCookieStorage object being used by the web view.

  • JavaScript (like the WKUserScript example you referenced) doesn’t see any cookies tagged with

    HttpOnly
    .
  • WKWebsiteDataStore lets you know of the existence of the cookie but doesn’t let you get the contents.

  • The delegate approach you showed (which I’d not seen before, so brav{o,a} for your creativity!) won’t see all the cookies because not all responses are navigation responses.

Under normal circumstances I’d recommend that you file an enhancement request requesting a better approach for this, but in this case I happen to know that WebKit Engineering is well aware of this issue (r. 31024691).

Right now the only approach that works in all cases is to use UIWebView, which is obviously less than ideal.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

How i get all (secure + http) cookie from webview can you help me ?