欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS修改UserAgent信息

程序员文章站 2022-05-09 13:49:43
...

UserAgent可以做什么?

  1. 检查浏览器或设备的功能,并根据结果加载不同的CSS;
  2. 将自定义JavaScript与另一个设备相比较;
  3. 与桌面计算机相比,向手机发送完全不同的页面布局;
  4. 根据用户代理语言偏好自动发送文档的正确翻译;
  5. 根据用户的设备类型或其他因素向特定用户推送特惠优惠;
  6. 收集有关访问者的统计信息,以告知我们的网页设计和内容制作流程,或者仅仅衡量谁访问我们的网站,以及来自哪些引荐来源。

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);
        }];
    }];