Best way to detect mobile device

Kailash Chandra Behera | Saturday, September 05, 2020

Introduction

This blog provides a code example for detecting device type in a web application using JavaScipt, here in this blog, we will see how to check if the request came from mobile or computer using JavaScript to the web application.

detecting device type in a web application

Best way to detect mobile device

Getting Started

The code example in this blog is applicable to any web application which supports JavaScript code. In the below code example we will see, the best way to detect mobile devices and how can a server-side know whether a client-side is a mobile device or PC.

 var isMobile = /iPhone|iPad|iPod|midp|rv:1.2.3.4|ucweb|windows ce|windows mobile|BlackBerry|IEMobile|Opera Mini|Android/i.test(navigator.userAgent);  

The above code is the key code or main building block to detect device type, it work as server-side device detector and it has capability of request browser detection.

The below code, renders a button which calls JavaScript function 'checkdevide'. The JavaScript code identifies requests coming from mobile or PC, here we are not identifying specific devices for example whether it's iPhone or iPod or which mobile, it only identifies that whether it runs in mobile devices or desktop browsers. But you can identify the specific device by modifying the code.

Example of How to know request from mobile or desktop

 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Device Borwser Detector</title>  
      <script type="text/javascript">  
      function checkdevide(){  
           var isMobile = /iPhone|iPad|iPod|midp|rv:1.2.3.4|ucweb|windows ce|windows mobile|BlackBerry|IEMobile|Opera Mini|Android/i.test(navigator.userAgent);  
                if (isMobile) {  
                alert("You are using Mobile");  
                } else {  
                     alert("You are using Desktop");  
                }  
           }  
      </script>  
 </head>  
 <body>  
 <h1>Device Borwser Detector</h1>  
 Check Device :<button onclick="checkdevide()" width="50" height="50">Check</button>  
 </body>  
 </html>  

Best way to detect mobile device

Copy the above complete code and paste it in notepad, save it as '.html'. Open the file in any browser and click on the button you will get the message whether the runs in mobile browser or desktop browser.

Related Articles

  1. Getting querystring value using Javascript
  2. Add new Row into HTML Table Using JQuery and Javascript
  3. Export HTML Table to Excel Using JavaScript

Thanks