4
votes

Our customer requested us to do a switch from WebView to WKWebView recently. Their app uses native login, which is done by a 2 POST calls to their backend, returning various authorization cookies that were later on used in every single HTTP/AJAX call throughout the whole app.

With the WebView, it all worked like a charm without a need to implement a single line of custom code. User logged in, cookies were stored to cookie storage by default, and WebView always took them from there and used them, since the HTTPCookieStorage was shared between NSURLSession and WebView.

It it a whole new story with WKWebView. Once we switched WebView to WKWebView, we saw that the authorization was not working. It was due to losing some cookies in the WKWebView. We store the cookies from the NSURLSession response now and append them to the WKWebView manually, by adding "Cookie" header to the HTTP requests.

We were able to get the authorization for HTTP calls work this way, but now we are seeing a new problem. Somehow, all the AJAX calls done in the WKWebView lose the authorization cookies.

Do you please know if there is any way to somehow have the authorization cookies appear in the AJAX calls too? Injecting javascript with

javascriptCookieString = @"document.cookie = 'testCookie=testValue';";  
[self.webView evaluateJavaScript:javascriptCookieString completionHandler:nil];

did not work and it seems like there is no control whatsoever over Javascript calls, so I cannot alter the requests before they are being executed. Thank you.

1
Did you found the fix ?Shauket Sheikh

1 Answers

5
votes

I found that the following snippet did the trick for us. We had the same problem.

// add session cookie to ajax calls
WKUserContentController* userContentController = 
WKUserContentController.new;
WKUserScript * cookieScript = 
        [[WKUserScript alloc]                                    
        initWithSource: [[User sharedInstance] getJavscriptCookieString]                                       
        injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];


[userContentController addUserScript:cookieScript];

WKWebViewConfiguration *webViewConfiguration = [[WKWebViewConfiguration alloc] init];
webViewConfiguration.userContentController = userContentController;
            webViewConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = true;

_wk = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfiguration];

The cookie string needs to be formated correct in order to be accepted.

-(NSString*) getJavscriptCookieString {
    return  [NSString stringWithFormat: @"document.cookie = '%@=%@'", [self getSessionName], [self getSessionValue]];
}

Hope this can be of some help.

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