js 判断所处平台
// 返回 android,ipad,iphone,macos,windows,AndroidTablet,linux
function getPlatform() {
const userAgent = window.navigator.userAgent;
let detectedPlatform = null;
if (/iPhone/i.test(userAgent) && !/iPad/i.test(userAgent)) {
detectedPlatform = 'iPhone';
} else if (/iPad/i.test(userAgent) || (isMac() && isTouchDevice())) {
detectedPlatform = 'iPad';
} else if (/Android/i.test(userAgent)) {
detectedPlatform = detectAndroidDevice(userAgent);
} else if (isMac()) {
detectedPlatform = 'Mac OS';
} else if (/Win32|Win64|Windows|WinCE/i.test(userAgent)) {
detectedPlatform = 'Windows';
} else if (/Linux/i.test(userAgent) && !/Android/i.test(userAgent)) {
detectedPlatform = 'Linux';
} else if (/CrOS/i.test(userAgent)) {
detectedPlatform = 'Chrome OS';
}
return detectedPlatform;
}
function isMac() {
return /Macintosh|MacIntel|MacPPC|Mac68K/i.test(window.navigator.userAgent);
}
function isTouchDevice() {
return 'ontouchend' in document;
}
function detectAndroidDevice(userAgent) {
// 使用用户代理字符串中的关键词来判断设备类型
if (/Mobile/i.test(userAgent)) {
// 如果用户代理中包含"Mobile",则可能是手机
return 'AndroidPhone';
} else if (/Tablet/i.test(userAgent)) {
// 如果用户代理中包含"Tablet",则可能是平板
return 'AndroidTablet';
} else {
// 如果用户代理中没有明确指出,使用屏幕尺寸作为辅助判断
if (window.screen.width >= 1024) {
return 'AndroidTablet';
} else {
return 'AndroidPhone';
}
}
}
