Member-only story

Five Methods to Detect Mobile Browsers in JavaScript

aifou
3 min readFeb 2, 2024

--

Sometimes, front-end web pages need to determine whether the user is using a mobile browser or a desktop browser.

This article, based on StackOverflow, compiles five methods for detecting mobile browsers using JavaScript.

1. navigator.userAgent

The simplest method is to analyze the browser’s user agent string, which contains device information. JavaScript uses the navigator.userAgent property to retrieve this string. If it contains keywords like 'Mobi', 'Android', 'iPhone', etc., the device can be identified as mobile.

if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
// Current device is a mobile device
}

// Alternate approach
if (
navigator.userAgent.match(/Mobi/i) ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/iPhone/i)
) {
// Current device is a mobile device
}

This method is convenient but unreliable since users can modify the user agent string to make a mobile browser appear as a desktop browser. Chromium-based browsers also have navigator.userAgentData for similar functionality, parsing the user agent string into an object with a mobile property indicating if the user is on a mobile device.

const isMobile = navigator.userAgentData.mobile;

--

--

aifou
aifou

No responses yet