ios - WKWebView AJAX 调用丢失 cookie

标签 ios objective-c ajax cookies wkwebview

我们的客户最近要求我们从 WebView 切换到 WKWebView。他们的应用程序使用 native 登录,这是通过对其后端的 2 POST 调用完成的,返回各种授权 cookie,这些 cookie 随后在整个应用程序的每个 HTTP/AJAX 调用中使用。

使用 WebView,这一切都非常有效,无需实现一行自定义代码。用户登录后,cookie 默认存储在 cookie 存储中,WebView 总是从那里获取并使用它们,因为 HTTPCookieStorage 在 NSURLSession 和 WebView 之间共享。

它是 WKWebView 的全新故事。将 WebView 切换为 WKWebView 后,我们发现授权不起作用。这是由于在 WKWebView 中丢失了一些 cookie。我们现在存储来自 NSURLSession 响应的 cookie,并通过将“Cookie” header 添加到 HTTP 请求来手动将它们附加到 WKWebView。

我们能够以这种方式获得 HTTP 调用的授权,但现在我们遇到了一个新问题。不知何故,在 WKWebView 中完成的所有 AJAX 调用都会丢失授权 cookie。

请问是否有任何方法可以让授权 cookie 也出现在 AJAX 调用中?注入(inject) javascript

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

不起作用,似乎无法控制 Javascript 调用,因此我无法在执行请求之前更改请求。谢谢。

最佳答案

我发现以下代码片段对我们有用。我们遇到了同样的问题。

// 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];

cookie 字符串需要格式正确才能被接受。

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

希望对您有所帮助。

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

关于ios - WKWebView AJAX 调用丢失 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674045/

相关文章:

php - Dropzone 在 Safari 和 IE 8 中不起作用

jquery - 使用 WCF 以及 jquery(AJAX) 和 html 客户端的文件上传服务

ios - iVar 未使用 ARC 释放

ios - 没有要搜索的对象但有条件的二进制搜索 NSArray

objective-c - 在静态单元格上使用 UIDatePicker

iphone - 如何让我的计时器在后台运行,然后发送本地通知?

c - HMAC-SHA1 的 Objective-C 示例代码

javascript - 显示 ajax 的响应不起作用

ios - 在两页模式下如何实现可缩放的 UIPageViewController?

ios - 如何在 iOS 应用程序中手动设置 "Back"目的地