本方法主要判断设备为手机、平板、异形屏(覆盖不全,能覆盖大多数)
export enum DEVICE {
PHONE = 'phone',
PAD = 'pad',
SPECIAL = 'special-shape'
}
function getPlatform () {
const userAgent = navigator.userAgent.toLowerCase()
// 已知的部分折叠屏设备的关键字列表
const foldableKeywords = [
'samsung galaxy z fold',
'samsung galaxy z flip',
'huawei mate x',
'huawei p50 pocket',
'motorola razr',
'oppo find n'
]
// 正则表达式:匹配三星折叠屏设备
const pattern = /sm-f\d{4}/
const clientWidth = document.documentElement.clientWidth
const clientHeight = document.documentElement.clientHeight
const min = Math.min(clientWidth, clientHeight)
const max = Math.max(clientWidth, clientHeight)
const aspectRatio = min / max
if (pattern.test(userAgent) || foldableKeywords.some(keyword => userAgent.includes(keyword))) {
// 折叠屏判断逻辑
if (aspectRatio < 0.85) {
return DEVICE.PHONE
} else {
// 宽高很接近时,判定为异型屏手机
return DEVICE.SPECIAL
}
} else {
// 非折叠屏走正常判断
const isIpad = /ipad/.test(userAgent)
// const isAndroidTablet = /android/.test(userAgent) && !/mobile/.test(userAgent) // 2025-08-01 Android Pad 正则有问题,会把折叠屏手机误判为平板
const isIpadOS = navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1
const specialSize = (clientWidth > 700 && clientHeight > 1000) || (clientWidth > 1000 && clientHeight > 700)
if (isIpad || isIpadOS || specialSize) {
return DEVICE.PAD
} else {
if (aspectRatio < 0.85) {
// if (isAndroidTablet) {
// return DEVICE.PAD
// }
return DEVICE.PHONE
} else {
// 宽高很接近时,判定为异型屏手机
return DEVICE.SPECIAL
}
}
}
}