美文网首页
获取WebView的UA并修改

获取WebView的UA并修改

作者: Else丶 | 来源:发表于2020-03-25 22:01 被阅读0次
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并修改

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