Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 21 May, 2021

Using CSS Media Queries, we can easily know that a user is currently viewing our website in 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.



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.


        /* 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("You are using a Mobile Device");
        } else {
            document.write("You are using Desktop");

Output: Following will be the output for desktop browser:

You are using Desktop
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!