在 decidePolicyForNavigationAction 中
- (void) webView:(WKWebView *)webView
decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
bool hasCookie = NO;
if([navigationAction.request allHTTPHeaderFields][@"Cookie"] ){
hasCookie = YES;
}
if(!hasCookie){
NSString *JSFuncString =
@"function setCookie(name,value,expires) {\
var oDate=new Date();\
oDate.setDate(oDate.getDate()+expires);\
document.cookie=name+'='+value+';expires='+oDate+';path=/'\
}";
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
RCTLogInfo(@"STORED COOKIE %@", [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies);
NSMutableString *JSCookieString = JSFuncString.mutableCopy;
for (NSHTTPCookie *cookie in cookieStorage.cookies) {
NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 3);", cookie.name, cookie.value];
[JSCookieString appendString:excuteJSString];
}
[webView evaluateJavaScript:JSCookieString completionHandler:nil];
decisionHandler(WKNavigationResponsePolicyAllow);
return ;
}