iOS开发中,前端H5想获知H5页面是在App内部还是在其他浏览器被打开,则需要客户端配合修改默认的UserAgent, 以便区分。在iOS8之前一直用的都是UIWebView,但是在iOS9出了一个WKWebView,对比起来前者UIWebview就具有严重的内存问题,UIWebView会被慢慢淘汰。
WKWebView修改UserAgent代码如下:
- (void)configWebViewUserAgent {
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero];
// 获取当前UserAgent, 并对其进行修改
[webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id userAgent, NSError * _Nullable error) {
if (![oldAgent isKindOfClass:[NSString class]]) {
// 为了避免没有获取到oldAgent,所以设置一个默认的userAgent
// Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
oldAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU iPhone OS %@ like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148", [[UIDevice currentDevice] model], [[[UIDevice currentDevice] systemVersion] stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
}
//自定义user-agent
NSString *newAgent = oldAgent;
if ([oldAgent rangeOfString:@"iOS_CFZQ_LEZHUAN"].location == NSNotFound) {
newAgent = [NSString stringWithFormat:@"%@; iOS_CFZQ_LEZHUAN_%@",oldAgent,[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
}
// 一定要设置customUserAgent,否则执行navigator.userAgent拿不到oldAgent
webView.customUserAgent = newAgent;
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
[[NSUserDefaults standardUserDefaults] synchronize];
}];
}];
}
切记:一定要设置customUserAgent,这行代码一定要写上。