DEV Community

Abdessalam Benharira
Abdessalam Benharira

Posted on • Updated on • Originally published at abdessalam.dev

Get current device type with JavaScript

When setting up some scripts, we need to know the current device type. Just take the example of analytics scripts or scripts that need to be loaded depending on the device. We will see through this article how to get the current device type with JavaScript using userAgent.

userAgent

userAgent is a property of the navigator object that indicates the user agent which the browser provides in HTTP headers.

With the value of this property we can test with a Regex if it contains some elements or not and then get the type of the device, tablet, mobile otherwise desktop. We can combine this test with the width of the current window.

Here is a function to get the device type

const getDeviceType = () => {
  const ua = navigator.userAgent;
  if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
    return "tablet";
  }
  if (
    /Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
      ua
    )
  ) {
    return "mobile";
  }
  return "desktop";
};
Enter fullscreen mode Exit fullscreen mode

userAgent cannot always give us the real device because it can be replaced easily, for example when we use bots the real device can be completely different from what is provided. And the same thing for browser infos. In this case, it will be better to check the availability or unavailability of some methods.

Let's try this function

desktop

desktop device detection javascript

tablet

tablet device detection javascript

mobile

mobile device detection javascript

Useful links

Before you leave…
Thanks for reading! 😊

Top comments (2)

Collapse
 
egeriis profile image
Ronni Egeriis Persson

Just noticed that the mobile regex contains check for "iPad", which should be caught in the previous check.

Collapse
 
itsabdessalam profile image
Abdessalam Benharira

Thanks! 🙌