修改useragent區(qū)分應用是在微信延都、瀏覽器雷猪,還是app內(nèi)運行
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;
}