# How to detect a mobile device with JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 1, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-detect-mobile-device

> A quick guide to learn how to detect if the browser is on a mobile device with JavaScript.


To detect if the user is using a mobile device in JavaScript, we can use the `userAgent` property. 

This property is part of the `navigator` object and sent by the browser in HTTP headers.  It contains information about the name, version, and platform of the browser.

With the value of `userAgent`, we can use a [regular expression](https://attacomsian.com/blog/javascript-regular-expressions) to test if it contains some keywords or not and then decide the type of the device (mobile, tablet, or desktop). Optionally, you can also combine this test with the width of the current window.

Here is a function that returns the type of device, the user is currently on:

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

Note that the above solution is **not always reliable**. The value of the `userAgent` can be easily changed. For example, when we use bots to scrape a website, we can pass a completely different user agent value to hide our identity. It will make it difficult to detect the actual device type.
