JavaScript

Detect Mobile / Device Type

by @admin
9h ago
Apr 28, 2026
Public
Detects whether the user is on a mobile, tablet, or desktop device. The navigator.userAgentData API (Chromium) is preferred for its structured data; falls back to a User-Agent regex for Safari and Firefox. Useful for conditional rendering, touch event handling, and analytics segmentation.
JavaScript
async function getDeviceType() {
  if (navigator.userAgentData) {
    const hints = await navigator.userAgentData.getHighEntropyValues(['mobile']);
    return hints.mobile ? 'mobile' : 'desktop';
  }
  const ua = navigator.userAgent;
  if (/tablet|ipad|playbook|silk/i.test(ua)) return 'tablet';
  if (/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/i.test(ua)) return 'mobile';
  return 'desktop';
}

// Usage
getDeviceType().then((type) => {
  console.log('Device:', type); // 'mobile', 'tablet', or 'desktop'
});
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.