Detecting if the user is on desktop or mobile in the browser

738 Views Asked by At

I have a web page and am trying to detect if the user is accessing the page on the desktop or on the mobile. What is the typical way to do this? Note I dont want to use the page width (e.g. window.innerWidth <= 767) to check as the user may simply have resized the desktop. Can someone assist in the best way to achieve this?

Thanks!

2

There are 2 best solutions below

0
Aria Noorghorbani On BEST ANSWER
// Check if the user is accessing the page on a mobile device
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

if (isMobile) {
  // User is accessing the page on a mobile device
  console.log("Mobile device detected");
} else {
  // User is accessing the page on a desktop device
  console.log("Desktop device detected");
}
0
xgiannak On

The mechanism planned for this purpose is the User-Agent field in HTTP header. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent but consider https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent where you will find javascript examples to test for specific features.

If you want to make tests with a client, look to https://whatmyuseragent.com/

Greetings, xg