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.




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>
   <title>Filtering the Non-unique characters</title>
   <h1 style="color: green;">
      Welcome To Tutorials Point
      /* 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>");


When the webpage is open on the desktop −

When the webpage is open on mobile −