Skip to content

Commit 4f8dd81

Browse files
author
Philipp Wallrich
committed
Added Cookie Handling
1 parent 7bf5e54 commit 4f8dd81

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

ios/RCTWKWebView/RCTWKWebView.m

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,11 +299,49 @@ - (void)stopLoading
299299
[_webView stopLoading];
300300
}
301301

302+
- (void) copyCookies {
303+
304+
NSHTTPCookieStorage* storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
305+
NSArray* array = [storage cookies];
306+
307+
308+
if (@available(ios 11,*)) {
309+
310+
// The webView websiteDataStore only gets initialized, when needed. Setting cookies on the dataStore's
311+
// httpCookieStore doesn't seem to initialize it. That's why fetchDataRecordsOfTypes is called.
312+
// All the cookies of the sharedHttpCookieStorage, which is used in react-native-cookie,
313+
// are copied to the webSiteDataStore's httpCookieStore.
314+
// https://bugs.webkit.org/show_bug.cgi?id=185483
315+
[_webView.configuration.websiteDataStore fetchDataRecordsOfTypes:[NSSet<NSString *> setWithObject:WKWebsiteDataTypeCookies] completionHandler:^(NSArray<WKWebsiteDataRecord *> *records) {
316+
for (NSHTTPCookie* cookie in array) {
317+
[_webView.configuration.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:nil];
318+
}
319+
}];
320+
} else {
321+
// Create WKUserScript for each cookie
322+
// Cookies are injected with Javascript AtDocumentStart
323+
for (NSHTTPCookie* cookie in array){
324+
NSString* cookieSource = [NSString stringWithFormat:@"document.cookie = '%@'", [self cookieDescription:cookie]];
325+
WKUserScript* cookieScript = [[WKUserScript alloc]
326+
initWithSource:cookieSource
327+
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
328+
329+
330+
[_webView.configuration.userContentController addUserScript:cookieScript];
331+
}
332+
}
333+
}
334+
302335
- (void)setSource:(NSDictionary *)source
303336
{
304337
if (![_source isEqualToDictionary:source]) {
305338
_source = [source copy];
306339
_sendCookies = [source[@"sendCookies"] boolValue];
340+
341+
if (_sendCookies) {
342+
[self copyCookies];
343+
}
344+
307345
if ([source[@"customUserAgent"] length] != 0 && [_webView respondsToSelector:@selector(setCustomUserAgent:)]) {
308346
[_webView setCustomUserAgent:source[@"customUserAgent"]];
309347
}

0 commit comments

Comments
 (0)