NeuroAgent

How to Detect Mobile Devices in JavaScript: Complete Guide

Learn how to create robust mobile device detection functions in JavaScript using regex patterns and specialized libraries like mobile-detect.js for responsive web development.

Question

How can I create a function that detects if a user is browsing on a mobile device?

I need a function that returns a boolean value indicating whether the user is using a mobile browser. While I’m aware that I could use navigator.userAgent with regular expressions to achieve this, I’m concerned about the wide variety of user-agent strings across different platforms and devices.

Is there a comprehensive solution or library that handles mobile browser detection reliably? I’ve looked at some existing resources, but the implementations are not clear enough for me to adapt into a simple true/false function.

What’s the best approach to create a robust mobile browser detection function in JavaScript?

NeuroAgent

To create a robust mobile browser detection function in JavaScript, you can use either regular expressions with navigator.userAgent or specialized libraries like mobile-detect.js or isMobile.js that provide more comprehensive and reliable detection. The best approach depends on your specific needs - simple regex patterns work for basic detection while dedicated libraries offer more accuracy and handle edge cases better, including tablets and various mobile browsers across different platforms.

Contents

Simple Mobile Detection Function

Creating a basic mobile detection function can be straightforward with regular expressions. Here’s a simple implementation that returns true for mobile devices:

javascript
function isMobile() {
  const regex = /Mobi|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
  return regex.test(navigator.userAgent);
}

// Usage
if (isMobile()) {
  console.log("Mobile device detected");
  // Redirect to mobile site or apply mobile-specific styles
}

This function uses a comprehensive regular expression that matches most common mobile device user agent strings. The pattern includes:

  • Mobi - Generic mobile identifier
  • Android - Android devices
  • webOS - WebOS devices
  • iPhone - Apple iPhones
  • iPad - Apple iPads
  • iPod - Apple iPods
  • BlackBerry - BlackBerry devices
  • IEMobile - Internet Explorer Mobile
  • Opera Mini - Opera Mini browser

Using Regular Expressions

Regular expressions provide a flexible approach to mobile detection. Here are some refined patterns:

javascript
// More comprehensive regex pattern
function isMobileAdvanced() {
  const regex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|Tablet/i;
  return regex.test(navigator.userAgent);
}

// Alternative approach - check for mobile keywords
function isMobileUserAgent() {
  const userAgent = navigator.userAgent || navigator.vendor || window.opera;
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
}

As mentioned in the Stack Overflow discussion, these regex patterns have been tested across various mobile browsers and platforms to ensure reliability.

For more robust mobile detection, consider using specialized libraries:

mobile-detect.js

The mobile-detect.js library is one of the most comprehensive solutions:

html
<script src="https://cdn.jsdelivr.net/npm/mobile-detect@2.1.0/mobile-detect.min.js"></script>
javascript
const md = new MobileDetect(window.navigator.userAgent);
const isMobile = md.mobile() !== null;

// Check for specific device types
const isPhone = md.phone();
const isTablet = md.tablet();
const isDesktop = !md.mobile();

// Check for specific operating systems
const isIOS = md.os() === 'iOS';
const isAndroid = md.os() === 'AndroidOS';

According to the library’s documentation, mobile-detect.js uses a combination of user agent parsing, feature detection, and device-specific checks to provide accurate detection.

isMobile.js

The isMobile.js library offers a simpler approach:

html
<script src="https://unpkg.com/is-mobile@1.0.0/isMobile.min.js"></script>
javascript
// Simple boolean return
if (isMobile()) {
  // Mobile device detected
}

// More detailed detection
const deviceInfo = isMobile;
console.log(deviceInfo); // Returns detailed device information

UAParser.js

For comprehensive browser and device detection, UAParser.js provides extensive information:

javascript
const parser = new UAParser();
const result = parser.getResult();
const isMobileDevice = result.device.type === 'mobile' || result.device.type === 'tablet';

Implementation Examples

Basic Implementation

javascript
/**
 * Detects if the user is browsing on a mobile device
 * @returns {boolean} True if mobile device detected, false otherwise
 */
function isMobileDevice() {
  // Check for common mobile user agent strings
  const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
  return mobileRegex.test(navigator.userAgent);
}

// Usage example
document.addEventListener('DOMContentLoaded', function() {
  if (isMobileDevice()) {
    document.body.classList.add('mobile-device');
    // Apply mobile-specific styles or functionality
  }
});

Advanced Implementation with media queries

javascript
/**
 * Detects mobile devices using multiple methods for better accuracy
 * @returns {boolean} True if mobile device detected
 */
function isMobileDeviceAdvanced() {
  // Method 1: User agent check
  const mobileRegex = /Mobi|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
  const isMobileUA = mobileRegex.test(navigator.userAgent);
  
  // Method 2: Touch screen detection
  const hasTouchScreen = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
  
  // Method 3: Screen size check (optional)
  const isSmallScreen = window.innerWidth <= 768;
  
  // Method 4: CSS media queries (most reliable)
  const isMobileMQ = window.matchMedia('(max-width: 768px)').matches;
  
  // Return true if any method indicates mobile
  return isMobileUA || (hasTouchScreen && isSmallScreen) || isMobileMQ;
}

// Usage
const deviceType = isMobileDeviceAdvanced() ? 'mobile' : 'desktop';
console.log('Device type:', deviceType);

Using mobile-detect.js in a React component

javascript
import React, { useEffect, useState } from 'react';
import MobileDetect from 'mobile-detect';

const MobileDetector = ({ children }) => {
  const [isMobile, setIsMobile] = useState(false);
  
  useEffect(() => {
    const md = new MobileDetect(window.navigator.userAgent);
    setIsMobile(md.mobile() !== null);
  }, []);
  
  return children({ isMobile });
};

// Usage
<MobileDetector>
  {({ isMobile }) => (
    <div className={isMobile ? 'mobile-view' : 'desktop-view'}>
      {/* Your content here */}
    </div>
  )}
</MobileDetector>

Best Practices and Considerations

Detection Accuracy

When implementing mobile detection, consider these factors:

  1. User Agent Limitations: As noted in the Stack Overflow discussion, user agent strings can be spoofed or incomplete, so relying solely on them isn’t always reliable.

  2. Tablet Detection: Decide whether tablets should be considered mobile devices. Most mobile detection libraries include tablets in their mobile detection.

  3. Progressive Enhancement: Use feature detection rather than device detection when possible.

Performance Considerations

javascript
// Cache the result to avoid repeated calculations
let mobileCache = null;

function isMobileCached() {
  if (mobileCache === null) {
    const regex = /Mobi|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
    mobileCache = regex.test(navigator.userAgent);
  }
  return mobileCache;
}

Error Handling

javascript
function isMobileSafe() {
  try {
    if (typeof navigator === 'undefined' || typeof navigator.userAgent === 'undefined') {
      return false; // Default to desktop in server-side environments
    }
    const regex = /Mobi|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
    return regex.test(navigator.userAgent);
  } catch (error) {
    console.error('Mobile detection error:', error);
    return false; // Fail safely
  }
}

Advanced Detection Methods

Using CSS Media Queries

The most reliable method is using CSS media queries:

javascript
function isMobileMediaQuery() {
  return window.matchMedia('(max-width: 768px)').matches;
}

// Or more comprehensive mobile detection
function isMobileDeviceMQ() {
  return window.matchMedia('(max-width: 768px) and (pointer: coarse)').matches;
}

Touch Screen Detection

javascript
function isTouchDevice() {
  return 'ontouchstart' in window || 
         navigator.maxTouchPoints > 0 || 
         navigator.msMaxTouchPoints > 0;
}

Device Orientation Detection

javascript
function isMobileOrientation() {
  return 'orientation' in window || 'orientation' in screen;
}

Combined Detection Strategy

javascript
/**
 * Comprehensive mobile detection using multiple methods
 * @returns {object} Device detection results
 */
function detectDevice() {
  const results = {
    isMobile: false,
    isTablet: false,
    isPhone: false,
    isDesktop: false,
    isIOS: false,
    isAndroid: false,
    userAgent: navigator.userAgent || ''
  };

  // User agent detection
  const mobileRegex = /Mobi|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
  const iosRegex = /iPhone|iPad|iPod/i;
  const androidRegex = /Android/i;
  
  results.isMobile = mobileRegex.test(results.userAgent);
  results.isIOS = iosRegex.test(results.userAgent);
  results.isAndroid = androidRegex.test(results.userAgent);

  // Screen size detection
  const isSmallScreen = window.innerWidth <= 768;
  const isMediumScreen = window.innerWidth > 768 && window.innerWidth <= 1024;
  
  results.isTablet = results.isMobile && isMediumScreen;
  results.isPhone = results.isMobile && isSmallScreen;
  results.isDesktop = !results.isMobile;

  return results;
}

// Usage
const device = detectDevice();
console.log('Device info:', device);

Sources

  1. Official mobile-detect.js Documentation - Device detection (phone, tablet, desktop, mobile grade, os, versions)
  2. GitHub - kaimallea/isMobile: A simple JS library that detects mobile devices
  3. JavaScript Mobile Detection - Stack Overflow
  4. UAParser.js - Detect Browser, Engine, OS, CPU, and Device type/model
  5. Detecting Mobile vs. Desktop Browsers in JavaScript - Medium
  6. Browser Detector & UserAgent Parser - CSS Script
  7. GitHub - hgoebl/mobile-detect.js
  8. How to detect mobile device using JavaScript - DEV Community
  9. Detect Mobile Device With Javascript (Simple Examples) - Code Boxx
  10. Top 10 Examples of mobile-detect code in Javascript - CloudDefense

Conclusion

Creating a robust mobile browser detection function requires balancing accuracy, performance, and maintainability. Here are the key takeaways:

  1. For simple needs: Use a well-crafted regular expression pattern that matches common mobile user agent strings, as shown in the basic implementation examples.

  2. For reliable detection: Use established libraries like mobile-detect.js or isMobile.js that handle edge cases and provide more comprehensive device information.

  3. For modern web applications: Consider using CSS media queries with JavaScript for the most accurate device detection, as this approach is less susceptible to user agent spoofing.

  4. For best results: Combine multiple detection methods (user agent, screen size, touch capabilities) to create a more robust solution that works across different scenarios.

  5. Remember: Mobile detection should complement, not replace, progressive enhancement techniques. Focus on providing functionality rather than device-specific experiences whenever possible.

Start with a simple implementation and gradually enhance it as you encounter specific detection challenges in your application. The library-based approaches provide the most comprehensive solution out-of-the-box while giving you the flexibility to customize the detection logic as needed.