JavaScript: How to Detect if a Website is Open on a Mobile or a Desktop?


We can use the CSS media queries to check whether the website is opened inside a web browser or a mobile browser. This information can be fetched using the min-width and the max-width of the webpage.

CSS media queries are only limited to styling the web pages but we can control the functionality of a website as per the user’s device by using the navigator properties in JavaScript.

The Navigator returns a set of values that includes user browser, version, operating system, and many more.

Syntax

navigator.userAgent

Example

In the below example, we are going to use Navigator to fetch the user’s device details. This will fetch us the major info that includes user browser, version, operating system, and more.

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Filtering the Non-unique characters</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      /* 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) {
         document.write("<h3>Its a Mobile Device !</h3>");
      } else {
         document.write("<h3>Its a Desktop !</h3>");
      }
   </script>
</body>
</html>

Output

When the webpage is open on the desktop −

When the webpage is open on mobile −

Updated on: 26-Apr-2022

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements