Monday, February 23, 2026
HomeLanguagesJavascriptHow to detect whether the website is being opened in a mobile...

How to detect whether the website is being opened in a mobile device or a desktop in JavaScript ?

Using CSS Media Queries, we can easily know which user is currently viewing our website on which device (using min-width and max-width). It is only limited to styling web pages, but we can control the functionality of the website according to the user’s device using the navigator userAgent Property in JavaScript.

We can get information about the user’s device. It returns a string containing the user browser’s name, version, operating system, etc.

Syntax:

navigator.userAgent 

Return Type: It returns the following string for a Windows desktop:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/90.0.4430.85 Safari/537.36

Example: Using this property, we can easily predict that it is opened on a Desktop or Mobile Device as shown in the below code.

Javascript




/* Storing user's device details in a variable*/
let details = navigator.userAgent;
  
/* Creating a regular expression 
containing some mobile devices keywords 
to search it in details string*/
let regexp = /android|iphone|kindle|ipad/i;
  
/* Using test() method to search regexp in details
it returns boolean value*/
let isMobileDevice = regexp.test(details);
  
if (isMobileDevice) {
    console.log("You are using a Mobile Device");
} else {
    console.log("You are using Desktop");
}


Output: Following will be the output for desktop browser:

You are using Desktop
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS