WKWebView如何添加cookie

最近做了一个项目,加载网页使用的是WKWebView,网页需要同步客户端登录后的cookie。

UIWebView加载cookie简述

在之前使用UIWebView时,因为UIWebView共用NSHTTPCookieStorage的cookie,h5页面同步cookie不需要做特别的处理。一般的流程是:登录请求成功后Cookie会自动保存在NSHTTPCookieStorage,然后将NSHTTPCookieStorage的cookie取出保存到NSUserDefaults,下次打开应用就将NSUserDefaults中保存的cookie设置到NSHTTPCookieStorage中,然后整个项目中发送的网络请求就都会带有设置的cookie。

当然UIWebView也可以设置request [request addValue:cookieValue forHTTPHeaderField:@"Cookie"]; 来添加cookie。

WKWebView添加cookie

到WKWebView后,它不会去获取NSHTTPCookieStorage中的cookie,就需要我们自己设置了。

首先在loadRequest的时候给request设置cookie

NSMutableString *cookieValue = [[NSMutableString alloc] initWithString:@"document.cookie = 'from=ios';"];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (NSHTTPCookie *cookie in [cookieJar cookies]) {
    NSString *appendString = [NSString stringWithFormat:@"%@=%@;", cookie.name, cookie.value];
    [cookieValue appendString:appendString];
}

[request addValue:cookieValue forHTTPHeaderField:@"Cookie"];

这样做了之后,在打开页面时是带有cookie的,也就是已登录的状态,但是当你点页面的链接跳转,新的页面却没有带上cookie。我们就要在初始化WKWebView时,在configuration中设置带有cookie的userContent。代码:

//各个WKWebview使用同一个WKProcesspool
config = [[WKWebViewConfiguration alloc] init];
config.preferences = [[WKPreferences alloc] init];
config.preferences.minimumFontSize = 10.0;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.processPool = [[WKProcessPool alloc] init];

//添加Cookie
NSMutableString *cookieValue = [[NSMutableString alloc] initWithString:@"document.cookie = 'from=ios';"];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (NSHTTPCookie *cookie in [cookieJar cookies]) {
    NSString *appendString = [NSString stringWithFormat:@"%@=%@;", cookie.name, cookie.value];
    [cookieValue appendFormat:@"document.cookie='%@';", appendString];
}

WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
                                initWithSource: cookieValue
                                injectionTime:WKUserScriptInjectionTimeAtDocumentStart                                  
                                forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];

config.userContentController = userContentController;

你可能感兴趣的:(WKWebView如何添加cookie)