简介
userAgent
中文名为用户代理,简称UA
,它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等。
userAgent
属性是一个只读的字符串,声明了浏览器用于HTTP
请求的用户代理头的值
应用
安卓系统
- 安卓系统的
userAgent
中会带有Android
标识
const ua = navigator.userAgent
const isAndroid = (ua.match(/Android/i) !== null)
IOS系统
- IOS系统的
userAgent
中会带有iPad
、iPod
或者iPhone
标识
let ua = navigator.userAgent.toLowerCase()
const isIos = (ua.match(/iPad|iPod|iPhone/i) !== null)
const isIphone = (ua.match(/iPhone/i) !== null)
微信浏览器
- 微信浏览器的
userAgent
中会带有Micromessenger
标识
let ua = navigator.userAgent.toLowerCase()
const isWechat = (ua.match(/micromessenger/i) !== null)
QQ浏览器
- QQ浏览器的
userAgent
中会带有qq/
标识
- QQ内部浏览器和QQ浏览器不太好区分
let ua = navigator.userAgent.toLowerCase()
const isQq = (ua.match(/\sqq\//i) !== null)
微博
let ua = navigator.userAgent.toLowerCase()
const isWeibo = (ua.match(/weibo/i) !== null)
其他
let u = navigator.userAgent
const UA = {
webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
mobile: !!u.match(/Mobile/), // 是否为移动终端
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
iosver: u.match(/CPU iPhone OS (\d+)\_(\d+) like/),
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或者uc浏览器
androidVer: u.substr(u.indexOf('Android') + 8, 3),
iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
iPad: u.indexOf('iPad') > -1, // 是否iPad
ga: u.indexOf('gameadvisor') > -1
}
mobile-detect
import MobileDetect from 'mobile-detect'
// 获取设备相关信息
export function getMobileInfo() {
// 获取userAgent信息
const ua = window.navigator.userAgent
// 初始化mobile-detect
const md = new MobileDetect(ua)
const mobile = md.mobile()
const os = md.os()
let model = ''
let version = ''
if (os === 'iOS') {
// ios系统的处理
version = md.version(mobile)
model = md.mobile()
} else if (os === 'AndroidOS') {
// Android系统的处理
version = md.version('Android')
const arr = ua.split(';')
for (const i in arr) {
if (arr[i].indexOf('Build/') > 0) {
model = arr[i].substring(0, arr[i].indexOf('Build/'))
break
}
}
}
return {
mobile: model,
os,
version,
browser: md.userAgent(),
network: getNetworkType()
}
}
// 获取设备的网络信息
function getNetworkType() {
const ua = navigator.userAgent
let networkStr = ua.match(/NetType\/\w+/) ? ua.match(/NetType\/\w+/)[0] : 'NetType/other'
networkStr = networkStr.toLowerCase().replace('nettype/', '')
let networkType
switch (networkStr) {
case 'wifi':
networkType = 'wifi'
break
case '4g':
networkType = '4g'
break
case '3g':
networkType = '3g'
break
case '3gnet':
networkType = '3g'
break
case '2g':
networkType = '2g'
break
default:
networkType = 'other'
}
return networkType
}
发表评论