UIWebView&WKWebView的UA设置

UIWebView的UA设置

在使用UIWebView时,更改user-agent,只能在原来系统UA后面添加一些东西,stackoverflow上面有一种方法:

http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk/23654363#23654363

 //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:@" Jiecao/2.4.7 ch_appstore"];
NSLog(@"new agent :%@", newAgent);
//regist the new agent
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

WKWebView的UA设置

也是stackover flow 上面的方法

@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:@" WeBank-Wepower/1.0.0"];
        
        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);
        }];
    }];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 用来修改的UA的webView 不要用来加载HTML ,不然起不到 UA更改的作用 参考链接 : http://w...
    MCWorld阅读 3,332评论 0 0
  • iOS8之后,苹果推出了WebKit这个框架,用来替换原有的UIWebView,新的控件优点多多,不一一叙述。由于...
    TIME_for阅读 18,462评论 63 143
  • 前言 关于UIWebView的介绍,相信看过上文的小伙伴们,已经大概清楚了吧,如果有问题,欢迎提问。 本文是本系列...
    CoderLF阅读 12,952评论 2 12
  • 通过学习,你将会学习以下几个方面的内容: **什么是WKWebView以及它和UIWebView的区别是什么 **...
    SOI阅读 14,026评论 18 42
  • 清晨随笔: 《我的四月天》 我在春光中漫步走来, 向低飞的燕子问声好, 向戏水的雏鸭打个招呼, 喂,温暖了,你们可...
    飘逸1阅读 3,762评论 2 9