前端 获取手机及设备类型

上一篇 前端 浏览器所在客户端信息,有浏览器信息后,以下是区分手机的详细类型

虽然没难度,但是记录下来,方便手续无脑复制:

苹果APP类型

1   // iOS
2   isIPhone = (userAgent: string) => /iphone/i.test(userAgent);
3   isIPod = (userAgent: string) => /ipod/i.test(userAgent);
4   isIPad = (userAgent: string) => /iPad/i.test(userAgent) || /Macintosh/i.test(userAgent);
5   public isIOS = (userAgent: string) => this.isIPhone(userAgent) || this.isIPod(userAgent) || this.isIPad(userAgent);

注:这里对ipad有添加额外的判断,Macintosh是一个新的iPad pro版本,用的操作系统是MAC,详细浏览器信息:

 1 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15 

安卓类型

大部分安卓的浏览器信息都有android字段

1   // android
2   public isAndroid = (userAgent: string) => /android/i.test(userAgent);

微信浏览器

1   // 微信
2   public isWechat = (userAgent: string) => /micromessenger/i.test(userAgent);
3   public isAppWechat = (userAgent: string) => this.isWechat(userAgent) && !/windowswechat/i.test(userAgent);

是否是手机端

添加mobile作为补充,当然直接使用mobile问题也不大

1   // 手机
2   public isMobile = (userAgent: string) => this.isAndroid(userAgent) || this.isIOS(userAgent) || /mobile/i.test(userAgent);

userAgent的字段介绍,可参考 其它博客浏览器的常见User Agent 各字段的解释

完整代码(可直接复制,不谢):

前端 获取手机及设备类型
 1 declare type UserAgentProvider = {
 2   isIOS: (userAgent: string) => void;
 3   isAndroid: (userAgent: string) => void;
 4   isMobile: (userAgent: string) => void;
 5   isWechat: (userAgent: string) => void;
 6 };
 7 
 8 class Index implements UserAgentProvider {
 9   // iOS
10   isIPhone = (userAgent: string) => /iphone/i.test(userAgent);
11   isIPod = (userAgent: string) => /ipod/i.test(userAgent);
12   isIPad = (userAgent: string) =>
13     /iPad/i.test(userAgent) || /Macintosh/i.test(userAgent);
14   public isIOS = (userAgent: string) =>
15     this.isIPhone(userAgent) ||
16     this.isIPod(userAgent) ||
17     this.isIPad(userAgent);
18 
19   // android
20   public isAndroid = (userAgent: string) => /android/i.test(userAgent);
21 
22   // 手机
23   public isMobile = (userAgent: string) => this.isAndroid(userAgent) || this.isIOS(userAgent) || /mobile/i.test(userAgent);
24 
25   // 微信
26   public isWechat = (userAgent: string) => /micromessenger/i.test(userAgent);
27   public isAppWechat = (userAgent: string) => this.isWechat(userAgent) && !/windowswechat/i.test(userAgent);
28 }
29 
30 export default new Index();
View Code

 

前端 获取手机及设备类型

上一篇:小米商城项目(JSP+Servlet项目)


下一篇:彻底解决安卓7.0及以上版本抓包https失败