美文网首页
解决WKWebView跨域,cookie不同步的问题

解决WKWebView跨域,cookie不同步的问题

作者: _菩提本无树_ | 来源:发表于2023-04-03 13:57 被阅读0次

第一步进来前将最初的URL地址进行存储为_mRemoteUrl

第二步跨域跳转时找到这个方法,这个方法必走

- (void)handleWebView:(WKWebView*)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler{}

第三步在这里获取host对比和之前url的host是否相同,相同不处理,不同进行处理

首先获取当前NSMutableURLRequest中是否有token
    NSMutableURLRequest *mutableRequest = navigationAction.request.mutableCopy;
    NSString *authKey = mutableRequest.allHTTPHeaderFields[@"Authorization"];
   //_mRemoteUrl之前的URL地址
    if (![authKey isEqualToString:_authKey] && [navigationAction.request.URL.host containsString:@"跨域的host地址例如  .baidu.com "]) {
        重置URL预防再次跨域
        _mRemoteUrl = absoluteString;
        [self reloadWebView];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }

reloadWebView

    //1.重新设置WKUserContentController
注意这个参数WKUserScriptInjectionTimeAtDocumentStart

    WKUserContentController * userContentController = self.webView.configuration.userContentController;
    userContentController = [self resetWKUserContentController:userContentController];
    self.webView.configuration.userContentController = userContentController;
    //2重置NSMutableURLRequest设置cookit
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_mRemoteUrl]];

    //应用于非 ajax 请求的 cookie 设置
    NSURL *myUrl = [[NSURL alloc] initWithString:_mRemoteUrl];
    NSString *cookie = [self setCookieWithHost:myUrl.host ajax:false];
    [mutableRequest addValue:cookie forHTTPHeaderField:@"Cookie"];
    
    [self.webView loadRequest:mutableRequest];

相关文章

网友评论

      本文标题:解决WKWebView跨域,cookie不同步的问题

      本文链接:https://www.haomeiwen.com/subject/pcndddtx.html