true-device
v1.0.1
Published
Accurate device detection library that goes beyond user-agent string
Maintainers
Readme
true-device
📦 ติดตั้ง
npm install true-device🚀 การใช้งาน
พื้นฐาน
import { getDevice } from 'true-device';
const device = getDevice();
console.log(device);
// {
// type: 'desktop',
// os: { name: 'Windows', version: '10' },
// browser: { name: 'Edge', version: '142.0.0.0' },
// isTouchDevice: false,
// screenWidth: 1920,
// screenHeight: 1080,
// userAgent: '...'
// }แสดง UI ตามอุปกรณ์
import { getDevice } from 'true-device';
const device = getDevice();
if (device.type === 'mobile') {
document.body.classList.add('mobile-layout');
} else if (device.type === 'tablet') {
document.body.classList.add('tablet-layout');
} else {
document.body.classList.add('desktop-layout');
}ตรวจสอบ Touch Support
import { getDevice } from 'true-device';
const device = getDevice();
if (device.isTouchDevice) {
document.addEventListener('touchstart', handleTouchStart);
} else {
document.addEventListener('mousedown', handleMouseDown);
}OS-Specific Features
import { getDevice } from 'true-device';
const device = getDevice();
if (device.os.name === 'iOS') {
showIOSInstallPrompt();
} else if (device.os.name === 'Android') {
showAndroidInstallPrompt();
}📖 API
getDevice(): DeviceInfo
ส่งคืนข้อมูลอุปกรณ์ทั้งหมด
interface DeviceInfo {
type: 'mobile' | 'tablet' | 'desktop';
os: { name: string; version: string; };
browser: { name: string; version: string; };
isTouchDevice: boolean;
screenWidth: number;
screenHeight: number;
userAgent: string;
}ฟังก์ชันแยกส่วน
import { checkPlatform, checkOS, checkBrowser, checkTouch } from 'true-device';
const type = checkPlatform(); // 'mobile' | 'tablet' | 'desktop'
const os = checkOS(); // { name: 'iOS', version: '17.0' }
const browser = checkBrowser(); // { name: 'Chrome', version: '142.0' }
const hasTouch = checkTouch(); // true | false🔬 วิธีการทำงาน
true-device ใช้หลายวิธีร่วมกัน:
- Touch Detection -
'ontouchstart' in window,navigator.maxTouchPoints - Screen Size -
window.screen.width/height - Platform API -
navigator.platform - User-Agent - Parse สำหรับ OS, Browser, Version
ตัวอย่าง: แก้ปัญหา iPad/Mac
// iPad (iOS 13+) รายงาน platform เป็น "MacIntel" แต่มี maxTouchPoints > 1
const isIPad = navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;🎨 ตัวอย่างการใช้งาน
React
import { getDevice } from 'true-device';
import { useState, useEffect } from 'react';
function App() {
const [device, setDevice] = useState(getDevice());
useEffect(() => {
const handleResize = () => setDevice(getDevice());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<div className={`app app--${device.type}`}>
{device.type === 'mobile' ? <MobileNav /> : <DesktopNav />}
</div>
);
}SSR (Server-Side Rendering)
🌍 Browser Support
- Chrome/Edge 90+
- Safari 14+
- Firefox 88+
- Opera 76+
- Modern browsers ที่รองรับ ES2020
📝 License
MIT © rratchapol
