0

我的要求是更新设置为WKWebView. 我可以更新 cookie NSHTTPCookieStorage,但相同的 cookie 不会反映到WKWebViewcookie(更新值存在NSHTTPCookieStorage但未设置为WKWebView

以下是我用来将该 cookie 设置为 AJAX 调用的代码。

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]) {
    [cookieString appendString:[NSString stringWithFormat:@"%@;", cookie.getCookieString]];
    [script appendString:[NSString stringWithFormat:@"document.cookie='%@';",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:NO];
[userContentController removeAllUserScripts];

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

更新 cookie 后,我尝试在我的 NSHTTPCookieStorage 中打印现有的 cookie,它显示了更新的值。

NSLog(@"cookies:%@",[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]);

我还尝试在更新 cookie 后打印脚本WKNavigationDelegate,但它显示旧值。

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"Script: %@",[wkWebView.configuration.userContentController.userScripts firstObject].source);

}
4

1 回答 1

0

以下代码解决了我的问题:

NSMutableString *script = [[NSMutableString alloc] init];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
    [script appendString:[NSString stringWithFormat:@"document.cookie='%@';",cookie.getCookieString]];
}
[wkwebView evaluateJavaScript:script completionHandler:^(id test, NSError *error){
    NSLog(@"test");
}];


-(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;
}
于 2016-07-13T06:40:09.093 回答