现在的位置: 首页 > 综合 > 正文

获取 UIWebview 的 Useragent,以及附加自定义字段到 Useragent

2018年04月19日 ⁄ 综合 ⁄ 共 962字 ⁄ 字号 评论关闭

获取 UIWebview 的useragent

关于获取 UIWebview 的useragent。我对网上的一种做法实在画面太美不忍看。他们使用UIWebview 去加载一个请求,通过返回来数据(附有 UserAgent 的参数)来获取Useragent,这种做法需要设置webview 代理、发请求、要解析数据、要处理用完的对象。

实际上只需要两行代码就能搞定

UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

<span style="font-size: 14px;">secretAgent</span>

这样我们就已经拿到了 useragent。

secretAgent值为: Mozilla/5.0 (iPhone; CPU iPhone OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D167


附加自定义字段到 Useragent中

NSString *newUagent = [NSString stringWithFormat:@"%@ appname/3.5.2",secretAgent];
NSDictionary *dictionary = [[NSDictionary alloc]
                                initWithObjectsAndKeys:newUagent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

这里我们附加的是appname,以及对应的版本号。

newUagent值为: Mozilla/5.0 (iPhone; CPU iPhone OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D167 appname/3.5.2

搞定!

厚吾http://blog.csdn.net/mangosnow

本文遵循“署名-非商业用途-保持一致”创作公用协议

抱歉!评论已关闭.