修改UserAgent判断运行坏境

修改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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容