What is the best way to detect a mobile device

Checking for a mobile device in a web app is a common requirement, but relying solely on user agent detection is not the best approach for modern web applications. Thankfully, there's a more robust alternative using the built-in JavaScript API for media detection.

window.matchMedia() method

The window.matchMedia() method serves as a valuable tool, allowing developers to create responsive designs by evaluating CSS media queries directly. This method returns a MediaQueryList object that reflects the outcome of a specified CSS media query string. By employing this approach, you can accurately detect mobile devices and their characteristics, enhancing the adaptability and user experience of your web application.

<script> $(document).ready(function(){ let isMobileDevice = window.matchMedia("only screen and (max-width: 760px)").matches; if(isMobileDevice){ // The viewport is less than 768 pixels wide //Conditional script here } else{ //The viewport is greater than 700 pixels wide alert("This is not a mobile device."); } }); </script>

You can use above script to do show/hide elements depending on the screen size.


detecting mobile device using javascript

Use Agent Detection (Not Recommended)

While using the user agent to detect mobile devices is relatively straightforward, it's not the most reliable method due to its susceptibility to manipulation. User agent strings can indeed be spoofed easily, which can lead to inaccurate results. Despite its simplicity, this method lacks the robustness needed for modern web development, particularly when security and accurate device detection are essential.

To get the user agent string, you can use the navigator.userAgent property.

var isMobileDevice = false; //initiate as false
// device detection if( /AndroidwebOSiPhoneiPadiPodBlackBerryIEMobileOpera Mini/i.test(navigator.userAgent) ) { //Conditional script here }

The userAgent value can be altered quite easily, even intentionally, which makes it an unreliable method for accurately identifying the actual device type. Bots and scrapers, among other tools, can manipulate the user agent value to conceal their true identity or characteristics. As a result, relying solely on the userAgent for device detection becomes even less trustworthy, emphasizing the need for more robust and secure techniques in modern web development.

Conclusion

To detect a mobile device using JavaScript, the user agent string is analyzed with a regular expression. This technique enables you to differentiate between mobile and non-mobile devices and tailor your website or application accordingly.