一、如何获取UserAgent
UIWebView方式:
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
DLog(@"userAgent :%@", userAgent);
WKWebView方式:
// 注意这个方法是异步的
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
[wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
DLog(@"userAgent :%@", result);
}];
默认UserAgent输出:
Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12H143
微信 iOS版的 :UserAgent
mozilla/5.0 (iphone; cpu iphone os 5_1_1 like mac os x) applewebkit/534.46 (khtml, like gecko) mobile/9b206 micromessenger/5.0
其中micromessenger就是自定义的
二、如何修改UserAgent
方案一,修改全局UserAgent值(这里是在原有基础上拼接自定义的字符串)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIWebView*webView = [[UIWebViewalloc]initWithFrame:CGRectZero];
NSString*userAgent = [webViewstringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString*newUserAgent = [userAgentstringByAppendingString:@" jdapp jdb2r"];//自定义需要拼接的字符串
NSDictionary*dictionary = [NSDictionarydictionaryWithObjectsAndKeys:newUserAgent,@"UserAgent",nil];
[[NSUserDefaultsstandardUserDefaults]registerDefaults:dictionary];
[[NSUserDefaultsstandardUserDefaults]synchronize];
}
方案二,自定义UserAgent值
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview: wkWebView];
NSString *customUserAgent = @"native_iOS";
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":customUserAgent}];
NSURL *url = [NSURL URLWithString:self.strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.f];
[self.wkWebView loadRequest:request];
方案三
self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
__weak typeof(self) weakSelf = self;
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
NSString *userAgent = result;
NSString *newUserAgent = [userAgent stringByAppendingString:@" native_iOS"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
// needs retain because `evaluateJavaScript:` is asynchronous
strongSelf.wkWebView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];
}];
[self.wkWebView loadRequest:request];
三、问题& 思考
在测试的时候,发现方案二、三第一次运行的时候,还是显示默认的值,第二次才会显示自定义的值,其中原因还不明,如有朋友解决麻烦告诉一下,谢谢。
作者:8870
链接:http://www.jianshu.com/p/5f02451b8e87
來源:
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。