published: 05 Sep 2022
2 min read
How to detect 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 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:
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.
Are we missing something? Help us improve this article. Reach out to us.
How to detect 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 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:
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.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur