JavaScriptmediumJavaScript

Device Detection

Detects user device type and browser information

01

The problem

Need to provide different features or styles based on user device type

02

The solution

JavaScript
const device = {
  // Detect device type
  isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  },
  
  isTablet() {
    return /iPad|Android(?!.*Mobile)|Tablet/i.test(navigator.userAgent);
  },
  
  isDesktop() {
    return !this.isMobile() && !this.isTablet();
  },
  
  isTouchDevice() {
    return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
  },
  
  // Detect operating system
  getOS() {
    const userAgent = navigator.userAgent;
    if (/Windows/i.test(userAgent)) return 'Windows';
    if (/Macintosh|Mac OS X/i.test(userAgent)) return 'MacOS';
    if (/Linux/i.test(userAgent)) return 'Linux';
    if (/Android/i.test(userAgent)) return 'Android';
    if (/iPhone|iPad|iPod/i.test(userAgent)) return 'iOS';
    return 'Unknown';
  },
  
  // Detect browser
  getBrowser() {
    const userAgent = navigator.userAgent;
    if (/Chrome/i.test(userAgent) && !/Edge/i.test(userAgent)) return 'Chrome';
    if (/Firefox/i.test(userAgent)) return 'Firefox';
    if (/Safari/i.test(userAgent) && !/Chrome/i.test(userAgent)) return 'Safari';
    if (/Edge/i.test(userAgent)) return 'Edge';
    if (/MSIE|Trident/i.test(userAgent)) return 'IE';
    return 'Unknown';
  },
  
  // Get screen information
  getScreenInfo() {
    return {
      width: window.screen.width,
      height: window.screen.height,
      availableWidth: window.screen.availWidth,
      availableHeight: window.screen.availHeight,
      colorDepth: window.screen.colorDepth,
      pixelRatio: window.devicePixelRatio || 1,
      orientation: window.screen.orientation?.type || 'landscape-primary'
    };
  },
  
  // Check for specific features
  supports: {
    localStorage: typeof window.localStorage !== 'undefined',
    sessionStorage: typeof window.sessionStorage !== 'undefined',
    geolocation: 'geolocation' in navigator,
    webGL: (() => {
      try {
        return !!window.WebGLRenderingContext && !!document.createElement('canvas').getContext('webgl');
      } catch {
        return false;
      }
    })()
  }
};

03

Put it to work

Example
console.log('Is mobile:', device.isMobile());
console.log('Operating System:', device.getOS());
console.log('Browser:', device.getBrowser());
console.log('Screen Info:', device.getScreenInfo());
console.log('Touch device:', device.isTouchDevice());
console.log('WebGL support:', device.supports.webGL);

// Device-specific logic
if (device.isMobile()) {
  console.log('Running on mobile device');
  // Mobile-specific code
} else if (device.isTablet()) {
  console.log('Running on tablet');
  // Tablet-specific code
} else {
  console.log('Running on desktop');
  // Desktop-specific code
}