Five Ways JavaScript Detects Mobile Browser

Five Ways JavaScript Detects Mobile Browser

Sometimes, the front-end web page needs to know whether the user is using a mobile browser or a desktop browser.

According to StackOverflow , this article organizes five methods for JavaScript to detect mobile browsers.

navigator.userAgent

The easiest way is to parse the browser’s user agent string, which contains device information.

JS navigator.userAgentgets this string through the attribute, as long as it contains keywords such as mobi , android, iphone etc., it can be identified as a mobile device.

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

// Another way to write
if (
  navigator.userAgent.match(/Mobi/i) ||
  navigator.userAgent.match(/Android/i) ||
  navigator.userAgent.match(/iPhone/i)
) {
  // Current device is mobile
}

The advantage of this method is that it is simple and convenient, but the disadvantage is that it is unreliable, because the user can modify this string to make the mobile browser disguise as a desktop browser.

Chromium-based browsers also have a navigator.userAgentDataproperty that has a similar effect. The difference is that it parses the user agent string into an object whose mobile properties return a boolean indicating whether the user is using a mobile device.

const isMobile = navigator.userAgentData.mobile; 

Note that Apple’s Safari and Firefox browsers do not support this property, see the Caniuse website for details .

In addition, there is a deprecated navigator.platformproperty that is supported by all browsers, so it can also be used. It returns a string representing the user’s operating system.

if (/Android|iPhone|iPad|iPod/i.test(navigator.platform)) {
  // Current device is mobile
}

window.screen,window.innerWidth

Another method is to judge whether it is a mobile phone by the screen width.

window.screen The object returns the screen information of the user’s device, and the widthproperty of this object is the screen width (in pixels).

if (window.screen.width < 500) {
  // Current device is mobile 
}

In the above example, if the screen width is window.screen.width less than 500 pixels, it is considered a mobile phone.

The disadvantage of this method is that it cannot be recognized if the phone is used in landscape orientation.

Another property window.innerWidth returns the width of the visible part of the web page in the browser window, which is more suitable for specifying the style of the web page under different widths.

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";
  }
};

window.orientation

The third method is to detect the screen orientation. The mobile phone screen can change the orientation (landscape or portrait) at any time, but the desktop device cannot.

window.orientation The property is used to get the current orientation of the screen. Only mobile devices have this property, and desktop devices will return undefined.

if (typeof window.orientation !== 'undefined') {
  // Current device is mobile  
}

Note that this property is not supported by the iPhone’s Safari browser.

touch event

The fourth method is that the DOM element of the mobile browser can specify the listener function ontouchstartfor the event through the attribute . touch Desktop devices do not have this property.

function isMobile() { 
  return ('ontouchstart' in document.documentElement); 
}

// Another way to write
function isMobile() {
  try {
    document.createEvent("TouchEvent"); return true;
  } catch(e) {
    return false; 
  }
}

window.matchMedia()

The last method is to combine CSS to judge.

CSS specifies responsive styles for web pages through media query. If a media query statement for the mobile phone takes effect, the current device can be considered to be a mobile device.

window.matchMedia() The method accepts a CSS media query statement as a parameter to determine whether the statement is valid.

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 is only valid for devices with a screen width of 700 pixels or less. It returns an object whose matches property is a boolean. 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, it can also be judged by the accuracy of the pointer.

let isMobile = window.matchMedia("(pointer:coarse)").matches;

In the above example, the CSS statement pointer:coarse indicates that the current device pointer is imprecise. Since the mobile phone does not support the mouse, but only supports touch, this condition is met.

Some devices support multiple pointers, such as mouse and touch at the same time. pointer:coarse It is only used to judge the main pointer, and there is also a any-pointercommand to judge all pointers.

let isMobile = window.matchMedia("(any-pointer:coarse)").matches;

In the above example, it any-pointer:coarse means that among all the pointers, as long as one pointer is inaccurate, the query condition is met.

Toolkit

In addition to the above methods, you can also use toolkits written by others. React-device-detect is recommended here , which supports device detection at various granularities.

import {isMobile} from 'react-device-detect';

if (isMobile) {
  // Current device is mobile  
}