javascriptbrowseruser-agent

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


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!


Solution

  • // 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");
    }