Friday, November 22, 2024
Google search engine
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

Recent Comments