WKWebView自定义UA(userAgent)的问题

话不多说,我赶时间,所以直接来一份代码吧。如果有不懂或者不清楚的欢迎大家留言,我会在看到后的第一时间回复你哦。

  1. 获取UA;
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"didFinishNavigation");
    
    self.launchScreenShowStart = [[NSDate date]timeIntervalSince1970];
    
    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSLog(@"userAgent :%@", result);
    }];
}

打印结果为:
userAgent :Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A403

  1. 自定义UA:
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.isYueTTAssistent) {
       
        if (@available(iOS 12.0, *)){
        //由于iOS12的UA改为异步,所以不管在js还是客户端第一次加载都获取不到,所以此时需要先设置好再去获取(1、如下设置;2、先在AppDelegate中设置到本地)
        NSString *baseAgent = @"Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15F79";
        NSString *userAgent = [NSString stringWithFormat:@"%@%@",baseAgent,CustomUserAgent];
        [self.kWKWebView setCustomUserAgent:userAgent];
    }

    //需要自定义UA
    @weakify(self);
    [self.kWKWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        @strongify(self);
        
        NSString *userAgent = result;
        NSString *newUserAgent;
        
        if (![result containsString:CustomUserAgent]) {
            
            newUserAgent = [userAgent stringByAppendingString:CustomUserAgent];
        }else{
            newUserAgent = result;
        }
        
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
        
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
        
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (@available(iOS 9.0, *)) {
            [self.kWKWebView setCustomUserAgent:newUserAgent];
        } else {
            // Fallback on earlier versions
            [self.kWKWebView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
        }
        
        //加载请求必须同步在设置UA的后面
       
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:self.url];
        
        [self.kWKWebView loadRequest:request];
        
    }];
    }else{
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:self.url];
        
        [self.kWKWebView loadRequest:request];
    }
}

再次打印结果为:

userAgent :Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A403;app/customeruseragent

  1. 如果你喜欢或者对你有帮助,别忘了给个赞哦。

你可能感兴趣的:(WKWebView自定义UA(userAgent)的问题)