一、UIWebView:
//1)获取默认userAgent:
UIWebView *uiwebView = [[UIWebView alloc] initWithFrame:CGRectZero];NSString *oldUA = *uiwebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
//2)设置userAgent:添加额外的信息
NSString *newUA = [NSString stringWithFormat:@"%@;%@", oldUA ,@"crf_app_ios_43];NSDictionary *dictNU = [[NSDictionary alloc] initWithObjectsAndKeys:newUA, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictNU];
二、WKWebView
异步方式
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _nullable result, NSError * _nullable error) {
//1)获取默认userAgent:
NSString *oldUA = result; //直接获取为nil
//2)设置userAgent:添加额外的信息
NSString *newUA = [NSString stringWithFormat:@"%@ crfapp/(%@)", oldUA , @"ios;43"];
NSDictionary *dictNU = [NSDictionary dictionaryWithObjectsAndKeys:newUA, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictNU];
}];
注:
1)UIwebvIew和WKWebView都是基于AppleWebkit内核,所获得UserAgent相同:Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Mobile/15B87
2)AppDelegate的applicationDidFinishLaunching:方法中,修改默认User Agent局限性:基于应用全局设置UserAgent,APP内访问的所有UIWebView及WKWebView将同步更新UA。
三、局部更新UserAgent:
//仅限于ios9.0以后版本,WKWebView设置customUserAgent
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _nullable result, NSError * _nullable error) {
//1)获取默认userAgent:
NSString *oldUA = result; //直接获取为nil ,需loadRequest
//2)设置userAgent:添加额外的信息
NSString *newUA =[NSString stringWithFormat:@"%@ crfapp/(%@)", oldUA , @"ios;43"];
self.wkWebView.customUserAgent = newUA;
}];
注:WKWebView 调用evaluateJavaScript方法获取UA或者设置UA时,需执行loadRequest方法,否则completionHandler result值为空
NSURL *url = [NSURL URLWithString:"h5Url"];NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.f];
[self.wkWebView loadRequest:request];