SmartCodingTips

📱 Device & Feature Detection in JavaScript

JavaScript can detect basic information about the device and browser using the navigator and other APIs. This helps tailor user experiences for different platforms or capabilities.

🔍 Detecting Device Type (Mobile, Tablet, Desktop)

You can use the navigator.userAgent or screen size to detect the type of device:

// User agent detection
const isMobile = /Mobi|Android/i.test(navigator.userAgent);
console.log("Is Mobile:", isMobile);

// Screen width detection
if (window.innerWidth < 768) {
    console.log("Likely a mobile device");
} else {
    console.log("Likely a desktop or tablet");
}

🛠️ Feature Detection

Feature detection helps check whether a browser supports a specific API or feature before using it.

// Check for localStorage support
if (typeof Storage !== "undefined") {
    console.log("localStorage is supported");
} else {
    console.log("localStorage NOT supported");
}

// Check for geolocation support
if ("geolocation" in navigator) {
    console.log("Geolocation is available");
} else {
    console.log("Geolocation is not supported");
}

🎤 Other Feature Examples

  • 'serviceWorker' in navigator – Check for Service Worker support
  • 'mediaDevices' in navigator – Access to camera and microphone
  • 'Notification' in window – Desktop Notification API support
  • 'Bluetooth' in navigator – Web Bluetooth support

⚠️ User Agent Limitations

User agent detection can be unreliable and spoofed. It's better to use feature detection when possible.

💡 Best Practice: Always prefer feature detection over device detection when handling cross-device compatibility.