/  Technology   /  How to detect a mobile device with JavaScript
How to detect a mobile device with JavaScript

How to detect a mobile device with JavaScript

 

With JavaScript we can detect whether our page or website is running on a web browser or on a mobile device. For verifying, we can use the below mentioned methods. It returns “mobile device” in console if the condition is true and if the page is opened in a mobile device or else if it opened in browser it returns “not a mobile device”.

 

<!DOCTYPE html>
<html>
<body>

<h4>How to detect a mobile device with JavaScript</h4>
<button onclick="isMobileDevice()">Click me</button>

<script>
  function isMobileDevice() {
    if( navigator.userAgent.match(/iPhone/i)
    || navigator.userAgent.match(/webOS/i)
    || navigator.userAgent.match(/Android/i)
    || navigator.userAgent.match(/iPad/i)
    || navigator.userAgent.match(/iPod/i)
    || navigator.userAgent.match(/BlackBerry/i)
    || navigator.userAgent.match(/Windows Phone/i)
    ){
       console.log("mobile device");
    }
    else {
      console.log("not a mobile device");
    }
   }
  </script>
</body>
</html>

 

In the above code, we have created a html file,Where in we are passing a function isMobileDevice() in the script tag. In the function we are passing two conditions that is (if and else). In the If block we used navigator.userAgent property in JavaScript This property navigates and returns the user-agent header sent by the browser to the server. This property is read-only. Hence it checks Whether the user has accessed the webpage using any mobile device or not. Within the if conditions, we are also giving the list of mobile devices with (OR) condition to check which device is being used and logging the statement “mobile device” if the condition returns true. Else we are logging “not a mobile device” if the condition returns false. The function isMobileDevice() executes when a button is clicked on the UI and prints the result in the console.

In this way we can detect a mobile device on a webpage or website using javaScript.

 

How to detect a mobile device with JavaScript

 

Leave a comment