Detect the user’s device type with a simple JavaScript check.
We do our best to design and code websites so that they look and perform the way they should regardless of device or browser, but the truth is sometimes we need to code for specific device, browser, or crawler. Whether it’s a quick hack or a simply wanting to display different content for a given device, we eventually need that information.
All major browser provides a very useful API to know the user’s device and the browser details.
window.navigator.userAgent
We can use this API-result in many ways.
The same browser-API can be used to identify the browser-type and thus identify the user’s device type ( mobile / tablet / desktop).
Regex Solution:
Here we have a very small function to detect, whether user is from a mobile device or not:
this function do consider all the cases and mobile-devices so that it will always works.
Here is another function to detect touch-enabled devices(for mobile or tablet)
This solution is based on mobile-phone detection algorithm of http://detectmobilebrowsers.com/
ReactJS Solution:
We can achieve this even more simpler, using this NPM package.
This package is itself a wrapper based on the same browser-API.