Detecting Mobile Devices: A JavaScript Approach

Detecting Mobile Devices: A JavaScript Approach

In this article, we will understand how to detect mobile devices in JavaScript.

Let's create a JavaScript function,

function isMobile() {
    var userAgent = window.navigator.userAgent;
    var mobilePatterns = [
        /Android/i,
        /webOS/i,
        /iPhone/i,
        /iPad/i,
        /iPod/i,
        /BlackBerry/i,
        /Windows Phone/i
    ];

    // Check if any of the mobile patterns match the user agent
    var isMobile = mobilePatterns.some(function(pattern) {
        return pattern.test(userAgent);
    });

    // If it's mobile, return true; if not, return false
    return isMobile;
}

Now let's understand the logic,

  • var userAgent = window.navigator.userAgent; :

    • This line returns the user agent string for the current browser.
  • var mobilePatterns :

    • The variable mobilePatterns is an array containing regular expressions designed to match specific keywords in the user agent string obtained from the browser. These patterns target common mobile device identifiers such as Android, iPhone, iPad, iPod, BlackBerry, Windows Phone, and webOS.
  • var isMobile :

    • The variable isMobile is a boolean that indicates whether the user agent string contains any of the predefined mobile device patterns, determined by applying the regular expressions in the mobilePatterns array to the userAgent.
  • return isMobile; :

    • Returning a boolean value indicating whether the user agent string matches any of the predefined mobile device patterns. If isMobile is true, it means the user is accessing the website from a mobile device, and false indicates a non-mobile device.

Now, let's call this function,

if (isMobile()) {
    alert("Mobile Device Detected!");
} else {
    alert("Is Not Mobile Device!");
}

Wrapping Up

Congratulations! We have successfully detected Mobile Devices using Web APIs, Regular Expressions in JavaScript.

Happy Coding!