[英]How to get cookies from WKWebView?
How do I get all cookies from a WKWebView instance? 如何从WKWebView实例获取所有 cookie?
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 . 我尝试使用
- [WKWebView evaluateJavaScript:completionHandler:]
来评估document.cookie
- 遗憾的是,结果不包含标记为HttpOnly的 cookie。
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
. 根据Modern WebKit API简介(WWDC 2014 Session 206) ,应该可以从
WKNavigation
的实例中获取response
对象。 However, according to the class reference , WKNavigation
does not contain any public method / property. 但是,根据类引用 ,
WKNavigation
不包含任何公共方法/属性。
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
. 您可以在
- webView:decidePolicyForNavigationResponse:decisionHandler:
WKNavigationDelegate
定义的方法中访问NSHTTPURLResponse
对象。 You can later extract the cookies manually from the HTTP header: 您可以稍后从HTTP标头手动提取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);
}
Please post your solution if you have a better one. 如果您有更好的解决方案,请发布您的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.