参考React Native的WKWebView配置,github地址https://github.com/react-native-community/react-native-webview/blob/master/ios/RNCWKWebView.m
网页将不再能获取默认的cookie,如果需要携带cookie,需要做一些操作:
if (self.window != nil && _webView == nil) {
WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
if (_incognito) {
wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
} else if (_cacheEnabled) {
wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
}
if(self.useSharedProcessPool) {
wkWebViewConfig.processPool = [[RNCWKProcessPoolManager sharedManager] sharedProcessPool];
}
wkWebViewConfig.userContentController = [WKUserContentController new];
if (_messagingEnabled) {
[wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
NSString *source = [NSString stringWithFormat:
@"window.%@ = {"
" postMessage: function (data) {"
" window.webkit.messageHandlers.%@.postMessage(String(data));"
" }"
"};", MessageHandlerName, MessageHandlerName
];
WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[wkWebViewConfig.userContentController addUserScript:script];
}
wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
#if WEBKIT_IOS_10_APIS_AVAILABLE
wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
? WKAudiovisualMediaTypeAll
: WKAudiovisualMediaTypeNone;
wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
#else
wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
#endif
if(_sharedCookiesEnabled) {
// More info to sending cookies with WKWebView
// https://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview/26577303#26577303
if (@available(iOS 11.0, *)) {
// Set Cookies in iOS 11 and above, initialize websiteDataStore before setting cookies
// See also https://forums.developer.apple.com/thread/97194
// check if websiteDataStore has not been initialized before
if(!_incognito && !_cacheEnabled) {
wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
}
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[wkWebViewConfig.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:nil];
}
} else {
NSMutableString *script = [NSMutableString string];
// Clear all existing cookies in a direct called function. This ensures that no
// javascript error will break the web content javascript.
// We keep this code here, if someone requires that Cookies are also removed within the
// the WebView and want to extends the current sharedCookiesEnabled option with an
// additional property.
// Generates JS: document.cookie = "key=; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"
// for each cookie which is already available in the WebView context.
/*
[script appendString:@"(function () {\n"];
[script appendString:@" var cookies = document.cookie.split('; ');\n"];
[script appendString:@" for (var i = 0; i < cookies.length; i++) {\n"];
[script appendString:@" if (cookies[i].indexOf('=') !== -1) {\n"];
[script appendString:@" document.cookie = cookies[i].split('=')[0] + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT';\n"];
[script appendString:@" }\n"];
[script appendString:@" }\n"];
[script appendString:@"})();\n\n"];
*/
// Set cookies in a direct called function. This ensures that no
// javascript error will break the web content javascript.
// Generates JS: document.cookie = "key=value; Path=/; Expires=Thu, 01 Jan 20xx 00:00:01 GMT;"
// for each cookie which is available in the application context.
[script appendString:@"(function () {\n"];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[script appendFormat:@"document.cookie = %@ + '=' + %@",
RCTJSONStringify(cookie.name, NULL),
RCTJSONStringify(cookie.value, NULL)];
if (cookie.path) {
[script appendFormat:@" + '; Path=' + %@", RCTJSONStringify(cookie.path, NULL)];
}
if (cookie.expiresDate) {
[script appendFormat:@" + '; Expires=' + new Date(%f).toUTCString()",
cookie.expiresDate.timeIntervalSince1970 * 1000
];
}
[script appendString:@";\n"];
}
[script appendString:@"})();\n"];
WKUserScript* cookieInScript = [[WKUserScript alloc] initWithSource:script
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:YES];
[wkWebViewConfig.userContentController addUserScript:cookieInScript];
}
}
_webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
注意
注入script时参数indectionTime有两个可选项WKUserScriptInjectionTimeAtDocumentStart
和WKUserScriptInjectionTimeAtDocumentEnd,
我们看一下官方文档对于这两个选项的解释:
WKUserScriptInjectionTimeAtDocumentStart
:注入时机为document的元素生成之后,其他内容load之前。
WKUserScriptInjectionTimeAtDocumentEnd:
注入时机为document全部load完成,任意子资源load完成之前。
一般情况下,如果想尽早注入cookie,在WKUserScriptInjectionTimeAtDocumentStart
时完成即可,但是有一种特殊情况,即目前的诊疗圈为后端渲染,数据请求依赖cookie中的sessionKey,
而前端页面的元素依赖后端返回的数据,因此,有一个问题,即cookie是在页面元素生成之后注入的,而在这之前,后端需要获取cookie,那么应该怎么办呢?
在requestHeader内注入cookie
NSString *cookie = @"cookieKey1=cookieValue1;cookieKey2=cookieValue2";
[mutableRequest addValue:cookie forHTTPHeaderField:@"Cookie"];
这样在网络请求开始时,requestHeader将携带cookie。