Skip to content

Instantly share code, notes, and snippets.

@Fi2zz
Created April 12, 2019 04:32
Show Gist options
  • Save Fi2zz/f6171d236d42e72157a44f7980f2f3cf to your computer and use it in GitHub Desktop.
Save Fi2zz/f6171d236d42e72157a44f7980f2f3cf to your computer and use it in GitHub Desktop.
WKWebView Ajax请求不带cookie的简单解决方案

在 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  ;
  }


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment