直接上代码:
第一种方法:
self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds]; __weak typeof(self) weakSelf = self; [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) { __strong typeof(weakSelf) strongSelf = weakSelf; NSString *userAgent = result; NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; strongSelf.webView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds]; // After this point the web view will use a custom appended user agent [strongSelf.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) { NSLog(@"%@", result); }]; }];
亲测结果:
Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36 Appended Custom User Agent
第二种方法:
UIWebView *webViews = [[UIWebView alloc] initWithFrame:self.view.bounds]; NSString *userAgent = [webViews stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds]; [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) { NSLog(@"%@", result); }];
结果:
Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36 Appended Custom User Agent
这种方法使UIWebView和WKWebView使用相同的用户代理,但这种方法可能会导致问题。