Detect a Mobile Device with JavaScript

02/01/2022

Contents

In this article, you will learn how to detect a mobile device with JavaScript.

JavaScript navigator object

To know the information of the connected user, use the JavaScript navigator object.
Information on user’s devices is stored in the navigator object, and each information can be acquired as a property.

Detect a mobile device

To determine if the connected device is a mobile, use the userAgent of the navigator object.

For example, when connected from iPhone, the following information is stored in userAgent.

 Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/577.01 
(KHTML, like Gecko) Version/6.8 Mobile/11A111 Safari/9788.91

Search for a character string from this information to determine whether it is amobile or tablet.

Below is sample code that uses the userAgent of the navigator object to detect if the connected device is mobile.

const ua = navigator.userAgent;

if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0){
// SmartPhone
}else if(ua.indexOf('iPad') > 0 || ua.indexOf('Android') > 0){
// Tablet
}else{
// Personal Computer
}