获取WebView的UA并修改

UIWebView获取方法:
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
//获取UA
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
//修改拼接UA
NSString *newAgent = [oldAgent stringByAppendingString:[NSString stringWithFormat:@" XXX/%@",AppVersion]];
//保存到本地
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];


WKWebView获取方法:
@property (nonatomic, strong) WKWebView *webView;

WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectZero];
//WKWebView需要先请求一个链接
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
__weak typeof(self) weakSelf = self;
[webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(NSString *oldAgent, NSError * _Nullable error) {
  NSString *newAgent = [oldAgent stringByAppendingString:[NSString stringWithFormat:@" XXX/%@",AppVersion]];
  NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
  [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
  [[NSUserDefaults standardUserDefaults]synchronize];
  //获取UA结束后,需要将WKWebView置空,避免内存泄露
  weakSelf.webView = nil;
}];
//需要赋值给一个强引用的属性,避免被提前释放
self.webView = webView;

你可能感兴趣的:(获取WebView的UA并修改)