Friday, September 5, 2025
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

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11861 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6699 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS