iOS修改UserAgent信息
程序员文章站
2022-05-09 13:49:43
...
UserAgent可以做什么?
- 检查浏览器或设备的功能,并根据结果加载不同的CSS;
- 将自定义JavaScript与另一个设备相比较;
- 与桌面计算机相比,向手机发送完全不同的页面布局;
- 根据用户代理语言偏好自动发送文档的正确翻译;
- 根据用户的设备类型或其他因素向特定用户推送特惠优惠;
- 收集有关访问者的统计信息,以告知我们的网页设计和内容制作流程,或者仅仅衡量谁访问我们的网站,以及来自哪些引荐来源。
UIWebView的UA设置
在使用UIWebView时,更改user-agent,只能在原来系统UA后面添加一些东西
//get the original user-agent of webview
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSLog(@"old agent :%@", oldAgent);
//add my info to the new agent
NSString *newAgent = [oldAgent stringByAppendingString:@"Bobo_Ma"];
NSLog(@"new agent :%@", newAgent);
//regist the new agent
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
WKWebView的UA设置
@property(nonatomic, strong) WKWebView *webView;
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
NSString *userAgent = result;
NSString *newUserAgent = [userAgent stringByAppendingString:@"Bobo_Ma"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
strongSelf.webView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];
strongSelf.webView.allowsBackForwardNavigationGestures = YES;
strongSelf.webView.UIDelegate = self;
strongSelf.webView.navigationDelegate = self;
if (nil != self.urlString) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];
[request setTimeoutInterval:15];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[strongSelf.webView loadRequest:request];
}
[strongSelf.view addSubview:self.webView];
// 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);
}];
}];
上一篇: iOS修改UserAgent
下一篇: Ocelot的使用(基本使用)