修改useragent区分应用是在微信、浏览器,还是app内运行
var userAgent = navigator.userAgent.toLowerCase();//获取UA信息
if(userAgent.indexOf("xxxx") != -1){//判断ua中是否含有和app端约定好的标识xxxx
alert(包含);
}else {
alert(不包含);
}
在userAgent后添加标识字段
H5页面获得的UserAgent都是默认的UserAgent,而不是修改后的UserAgent,原因在于webView会将userAgent替换为默认。
直接在加载webView处更改无效,故而我们在AppDelegate里面的- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions方法里修改默认的UserAgent。该方法能保证userAgent成功被修改。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//修改userAgent,在后面添加字段
UIWebView * tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString * oldAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString * newAgent = oldAgent;
//此处在userAgent后添加加* dbios/版本号*
if (![oldAgent hasSuffix:@" dbios"]) {
newAgent = [oldAgent stringByAppendingString:[NSString stringWithFormat:@" dbios/%@",xxxx]];// xxxx为和h5约定的标示
}
NSLog(@"new agent :%@", newAgent);
NSDictionary * dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
[[NSUserDefaults standardUserDefaults] synchronize];
return YES;
}