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.


  • 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.

    链接地址: http://www.djcxy.com/p/24474.html

    上一篇: 如何检查一个svn命令是否需要验证

    下一篇: 如何从WKWebView获取cookies?