如何从 WKWebView 实例获取所有 cookie?
到目前为止,这是我尝试过的:
我尝试使用
- [WKWebView evaluateJavaScript:completionHandler:]
来评估document.cookie
- 不幸的是,结果不包含标记为 HttpOnly 的 cookie .根据 Introducing the Modern WebKit API (WWDC 2014 Session 206) ,应该可以从
WKNavigation
的实例中获取一个response
对象。然而,根据class reference ,WKNavigation
不包含任何公共(public)方法/属性。
最佳答案
由于这个问题在一年后仍未得到解答,因此我发布了我的不完美但有效的解决方案:
您可以访问 NSHTTPURLResponse
- webView:decidePolicyForNavigationResponse:decisionHandler:
中的对象在 WKNavigationDelegate
上定义的方法.您可以稍后从 HTTP header 中手动提取 cookie:
- (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);
}
如果您有更好的解决方案,请发布您的解决方案。
关于ios - 如何从 WKWebView 获取 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28232963/