How to detect whether the website is being opened in a mobile device or a desktop in JavaScript ?
Last Updated :
17 Feb, 2023
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
let details = navigator.userAgent;
let regexp = /android|iphone|kindle|ipad/i;
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
Share your thoughts in the comments
Please Login to comment...