DEV Community

Cover image for Five methods for JavaScript to detect mobile browsers
Sabesan Sathananthan
Sabesan Sathananthan

Posted on

Five methods for JavaScript to detect mobile browsers

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 , this article sorts out five methods for JavaScript to detect mobile browsers.
Photo by Jenny Smith on Unsplash


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.




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
}


Enter fullscreen mode Exit fullscreen mode

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.



const isMobile = navigator.userAgentData.mobile; 


Enter fullscreen mode Exit fullscreen mode

Note that Apple's Safari browser and Firefox browser do not support this attribute. you can check the CanIUse website for more details.

In addition, there is an abolished navigator.platform property, which is supported by all browsers, so it can also be used. It returns a string that represents the user's operating system.



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


Enter fullscreen mode Exit fullscreen mode

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).



if (window.screen.width < 500) {
  // The current device is a mobile device
}


Enter fullscreen mode Exit fullscreen mode

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.



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


Enter fullscreen mode Exit fullscreen mode

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.



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


Enter fullscreen mode Exit fullscreen mode

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.



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

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


Enter fullscreen mode Exit fullscreen mode

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.



let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;


Enter fullscreen mode Exit fullscreen mode

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.



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


Enter fullscreen mode Exit fullscreen mode

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.



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


Enter fullscreen mode Exit fullscreen mode

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, which supports device detection with multiple granularities.



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

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


Enter fullscreen mode Exit fullscreen mode

Top comments (0)