and*_*cek 4 cookies ajax objective-c ios wkwebview
我们的客户最近要求我们从 WebView 切换到 WKWebView。他们的应用程序使用本机登录,这是通过对后端的 2 次 POST 调用完成的,返回各种授权 cookie,这些 cookie 稍后在整个应用程序的每个 HTTP/AJAX 调用中使用。
使用 WebView,无需实现单行自定义代码,一切都变得非常迷人。用户登录后,cookie 默认存储到 cookie 存储中,WebView 总是从那里获取并使用它们,因为 HTTPCookieStorage 在 NSURLSession 和 WebView 之间共享。
WKWebView 是一个全新的故事。一旦我们将 WebView 切换到 WKWebView,我们看到授权不起作用。这是由于在 WKWebView 中丢失了一些 cookie。我们现在存储来自 NSURLSession 响应的 cookie,并通过向 HTTP 请求添加“Cookie”标头来手动将它们附加到 WKWebView。
我们能够以这种方式获得 HTTP 调用的授权,但现在我们看到了一个新问题。不知何故,在 WKWebView 中完成的所有 AJAX 调用都会丢失授权 cookie。
您是否知道是否有任何方法可以让授权 cookie 也出现在 AJAX 调用中?注入javascript
javascriptCookieString = @"document.cookie = 'testCookie=testValue';";
[self.webView evaluateJavaScript:javascriptCookieString completionHandler:nil];
Run Code Online (Sandbox Code Playgroud)
不起作用,似乎无法控制 Javascript 调用,因此我无法在执行请求之前更改请求。谢谢你。
小智 5
我发现以下代码段对我们有用。我们遇到了同样的问题。
// 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];
Run Code Online (Sandbox Code Playgroud)
cookie 字符串的格式必须正确才能被接受。
-(NSString*) getJavscriptCookieString {
return [NSString stringWithFormat: @"document.cookie = '%@=%@'", [self getSessionName], [self getSessionValue]];
}
Run Code Online (Sandbox Code Playgroud)
希望这可以有所帮助。
另请参阅: 我可以设置 WKWebView 使用的 cookie 吗?
归档时间: |
|
查看次数: |
4331 次 |
最近记录: |