Five methods for JavaScript to detect mobile browsers
Tags: javascript, webdev, programming, tutorial
Published: 2021-10-15 08:34:44

If you are a front-end developer you need to know whether the user is using a mobile browser or a desktop browser. Based on [StackOverflow](https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser) , this article sorts out five methods for JavaScript to detect mobile browsers.
![Photo by Jenny Smith on Unsplash](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv60x65dkj0olgo0p7he.jpg)

---

## __1. `navigator.userAgent`__
The easiest way is to analyze the user agent string of the browser, which contains the device information.
JS gets this string through the `navigator.userAgent` property, as long as it contains keywords such as `mobi`, `android`, `iphone`, etc. It can be identified as a mobile device.
```JS

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

// Another way of writing
if (
  navigator.userAgent.match(/Mobi/i) ||
  navigator.userAgent.match(/Android/i) ||
  navigator.userAgent.match(/iPhone/i)
) {
  // The current device is a mobile device
}
```
The advantage of this method is simple and convenient, but the disadvantage is that it is unreliable. The user can modify this string to make the mobile browser pretend to be a desktop browser.

Chromium browsers also have a `navigator.userAgentData` property, which has a similar effect. The difference is that it parses the user agent string into an object and the `mobile` attribute of the object returns a Boolean value indicating whether the user is using a mobile device.
```JS
const isMobile = navigator.userAgentData.mobile; 
```
Note that Apple's Safari browser and Firefox browser do not support this attribute. you can check the [CanIUse website](https://caniuse.com/mdn-api_navigator_useragentdata) for more details.

In addition, there is an abolished [`navigator.platform`](https://stackoverflow.com/questions/19877924/what-is-the-list-of-possible-values-for-navigator-platform-as-of-today) property, which is supported by all browsers, so it can also be used. It returns a string that represents the user's operating system.
```JS
if (/Android|iPhone|iPad|iPod/i.test(navigator.platform)) {
  // The current device is a mobile device
}
```
---
## __2. `window.screen`, `window.innerWidth`__
Another method is to determine whether it is a mobile phone by the width of the screen.

The `window.screen` object returns the screen information of the user device. The `width` property of this object is the width of the screen (in pixels).
```JS
if (window.screen.width < 500) {
  // The current device is a mobile device
}
```
In the above example, if the screen width `window.screen.width` is less than 500 pixels, it is considered a mobile phone. The disadvantage of this method is that if the mobile phone is used horizontally, it cannot be recognized.

Another property window.innerWidth returns the width of the visible part of the webpage in the browser window, which is more suitable for specifying the style of the webpage under different widths.
```JS
const getBrowserWidth = function() {
  if (window.innerWidth < 768) {
    return "xs";
  } else if (window.innerWidth < 991) {
    return "sm";
  } else if (window.innerWidth < 1199) {
    return "md";
  } else {
    return "lg";
  }
};
```
---
## __3. `window.orientation`__
The third method is to detect the orientation of the screen. The phone screen can change its orientation (horizontal or vertical) at any time, but it cannot be done on desktop devices.

The `window.orientation` property is used to get the current orientation of the screen. Only mobile devices have this property. Desktop devices will return `undefined`.
```JS
if (typeof window.orientation !== 'undefined') {
  // The current device is a mobile device
}
```
> _Note that the iPhone’s Safari browser does not support this attribute._

---
## __4. touch event__
The fourth method is that the DOM element of the mobile browser can specify the listener function for the touch event through the ontouchstart attribute. Desktop devices do not have this attribute.
```JS
function isMobile() { 
  return ('ontouchstart' in document.documentElement); 
}

// Alternative way of writing
function isMobile() {
  try {
    document.createEvent("TouchEvent"); return true;
  } catch(e) {
    return false; 
  }
}
```

---
## __5. `window.matchMedia()`__
The last method is to judge with CSS.

CSS uses media query (media query) to specify responsive styles for web pages.If a certain media query statement for a mobile phone takes effect, the current device can be considered as a mobile device.The `window.matchMedia()` method accepts a CSS media query statement as a parameter to determine whether this statement is valid.
```JS
let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
```
In the above example, the parameter of `window.matchMedia()` is a CSS query statement, which means that it only takes effect on devices with a screen width of no more than 760 pixels. It returns an object whose `matches` attribute is a boolean value. If it is `true`, it means that the query is valid and the current device is a mobile phone.

In addition to judging by the screen width, you can also judge by the accuracy of the pointer.
```JS
let isMobile = window.matchMedia("(pointer:coarse)").matches;
```
In the above example, the CSS statement `pointer:coarse` indicates that the pointer of the current device is imprecise. Since the mobile phone does not support the mouse, it only supports touch, so it meets this condition.

Some devices support multiple pointers, such as mouse and touch at the same time. `pointer:coarse` is only used to determine the primary pointer, and there is also an `any-pointer` command to determine all pointers.
```JS
let isMobile = window.matchMedia("(any-pointer:coarse)").matches;
```
In the above example, `any-pointer:coarse` means that among all the pointers. As long as one pointer is inaccurate, it meets the query conditions.

---

## __6. Toolkit__
In addition to the above methods, you can also use a toolkit written by others.Recommended here is [react-device-detect](https://www.npmjs.com/package/react-device-detect), which supports device detection with multiple granularities.
```JS
import {isMobile} from 'react-device-detect';

if (isMobile) {
  // The current device is a mobile device
}
```