Durga Prasad Vundavalli Durga Prasad Vundavalli - 5 months ago 108
Objective-C Question

WKWebView Cookies

I'm using the below mentioned approach to set cookies in a

WKWebview
:
Can I set the cookies to be used by a WKWebView?

But the cookies that I have set are being duplicated in the AJAX calls. I mean they are being repeated twice.

Here is the code snippet that I used:

NSString *strURL = DASHBOARDURL;
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];

NSMutableString *script = [[NSMutableString alloc] init];
NSMutableString *cookieString = [[NSMutableString alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[script appendString:[NSString stringWithFormat:@"document.cookie='%@';",cookie.getCookieString]];
[cookieString appendString:[NSString stringWithFormat:@"%@;", cookie.getCookieString]];
}
[request setValue:cookieString forHTTPHeaderField:@"Cookie"];

//cookies for further AJAX calls
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
WKUserScript *cookieInScript = [[WKUserScript alloc] initWithSource:script
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:YES];
[userContentController addUserScript:cookieInScript];

WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init];
webViewConfig.userContentController = userContentController;

CGRect viewRect = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);

wkWebview = [[WKWebView alloc] initWithFrame:viewRect configuration:webViewConfig];
wkWebview.navigationDelegate = self;
[wkWebview loadRequest:request];
[self.view addSubview:wkWebview];


getCookieString
is a method that returns cookie values as an
NSString



  1. Will the
    WKWebView
    set the cookies back to
    NSHTTPCookieStorage

    at runtime(During AJAX calls)

  2. Can i control AJAX calls cookies with any delegate methods?

    Removing
    domain=
    from my getCookieString method fixed the issue


    -(NSString *)getCookieString {
    NSString *string = [NSString stringWithFormat:@"%@=%@;expiresDate=%@;path=%@;sessionOnly=%@;isSecure=%@",
    self.name,
    self.value,
    self.expiresDate,
    self.path ?: @"/",
    self.isSecure ? @"TRUE":@"FALSE",
    self.sessionOnly ? @"TRUE":@"FALSE"];
    return string;
    }


Answer

Multiple Cookies are sent if there are more than one cookie in the cookie store whose domains (or paths) match the requested URL.

Whilst writing your getCookieString method you may have changed or added the domain= part of the string. This would cause a second valid cookie to be stored and therefor sent with your request.

Comments