作者:霸气的饭桶丶_130 | 来源:互联网 | 2023-09-17 14:02
前端获取操作系统、操作系统版本在做埋点的过程中,遇到要上传操作系统和操作系统版本的需求,如下通过navigator.userAgent获取首先将操作系统确定为如下映射:ALL_OS
前端获取操作系统、操作系统版本
在做埋点的过程中,遇到要上传操作系统和操作系统版本的需求,如下

通过navigator.userAgent
获取
首先将操作系统确定为如下映射:
ALL_OS = {
WINDOWS: 'windows',
WINDOWSPHONE: 'windows phone',
IPHONE: 'iphone',
IPAD: 'ipad',
MAC: 'mac',
ANDROID: 'android',
OTHERS: 'others',
}
获取当前操作系统
/** 获取当前操作系统 */
export const getOS = () => {
let os = ALL_OS.OTHERS
const userAgent = navigator.userAgent
if (userAgent.includes('Windows NT')) {
os = ALL_OS.WINDOWS
}
if (userAgent.includes('Mac')) {
if (userAgent.includes('iPhone')) {
os = ALL_OS.IPHONE
} else if (userAgent.includes('iPad')) {
os = ALL_OS.IPAD
} else {
os = ALL_OS.MAC
}
}
if (userAgent.includes('Android')) {
os = ALL_OS.ANDROID
}
return os
}
获取操作系统版本
/** 获取系统版本 */
export const getOSVersion = () => {
const os = getOS()
let osVersion = ALL_OS.OTHERS
const userAgent = navigator.userAgent
if (os === ALL_OS.IPHONE) {
osVersion = userAgent.slice(userAgent.indexOf(';') + 2, userAgent.indexOf(')'))
return osVersion
}
if (os === ALL_OS.IPAD) {
osVersion = userAgent.slice(userAgent.indexOf(';') + 2, userAgent.indexOf(')'))
return osVersion
}
if (os === ALL_OS.WINDOWS) {
osVersion = userAgent.slice(userAgent.indexOf('(') + 1, userAgent.indexOf(';'))
return osVersion
}
if (os === ALL_OS.MAC) {
// todo
}
if (os === ALL_OS.ANDROID) {
const middle = userAgent.slice(userAgent.indexOf(';') + 2, userAgent.indexOf(')'))
osVersion = middle.slice(0, middle.indexOf(';'))
return osVersion
}
return osVersion
}