loading...

Get current device type with JavaScript

itsabdessalam profile image Abdessalam Benharira Originally published at abdessalam-benharira.me Updated on ・2 min read

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|ad)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
      ua
    )
  ) {
    return "mobile";
  }
  return "desktop";
};

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! 😊

Discussion

pic
Editor guide