Sometimes we need a little Javascript code snippet to detect if user use mobile device, the simplest way is detecting its browser user agent.
We use the regular expression test to detect if browser is a mobile device like:
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
// true for mobile device
document.write("mobile device");
}else{
// false for not mobile device
document.write("not mobile device");
}
demo is on codepen:
https://codepen.io/timhuang/pen/MWKEZMJ
Reference:
https://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device
Top comments (34)
Hey,
this is very very unreliable. UserAgent can be changed and as far as I know, iPads want to be treated as desktops now and thus send the same UA in Safari as the Desktop Safari.
Mozilla is of a similar opinion:
developer.mozilla.org/en-US/docs/W...
Hope that helps :-)
I didn't read your link, if you provided a solution using that link, my apologies. Otherwise, do you have a better solution? I'm thinking you do ;-)
That link shows that using UserAgent is unreliable. If you trust my comment you don't need to read the source :-)
In one of our projects, we have a workaround that checks for screen size, pixel density, touch and other features only available on mobile devices. It seems to work reliably, but it is an Angular module, that I can't share at the moment. Unfortunately, we don't have a plain JS solution yet. That's also the reason why I did search for a simpler way again (for a non-angular project) and found your solution. At first, I was amazed, but then I realized that we have tried this approach in the past and it was not reliable enough for what we needed. So I just wanted to leave this comment here, so people know about it. For this project, I'm back to simple breakpoints considering the width of the screen.
"Browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable."
If we require that users don't modify their UserAgent in order to use our website then the UserAgent is perfectly reliable!
I agree with @bechtold , using the user agent is a bad idea, there are multiple features to consider, I recommend this article on how to use media queries in JavaScript, I think it is a bester practice.
"using the user agent is a bad idea, there are multiple features to consider"
Would you elaborate on why using the user agent is a bad idea? (Also, I'm not sure if you meant features or some other word.)
@jeancarlo13 the problem with using media queries in JS is that it causes layout shift (FOUC) and it's a problem mainly on above-the-fold UI. Otherwise it's a good approach.
You can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query.
if (window.matchMedia("(max-width: 767px)").matches)
{
// The viewport is less than 768 pixels wide
document.write("This is a mobile device.");
}
You may also use navigator.userAgentData.mobile .
const isMobile = navigator.userAgentData.mobile;
Another approach would be a responsive media query. You could presume that a mobile phone has a screen size greater than x and less than y. For example:
@media only screen and (min-width: 320px) and (max-width: 600px) {}
net-informations.com/js/iq/default...
Unfortunately navigator.userAgentData.mobile appears to be not widely supported yet
caniuse.com/?search=userAgentData
caniuse.com/?search=mobile
Thanks for sharing!
Thank you for this,
I have ended up placing it in a view class as a getter function
Honestly thanks for this eloquent regex test.
thanks for your improvement! :)
Make it shorter like this:
Thank you!
Wow, really short! Thanks for your improvement.
Alternatively, you can use
navigator.mediaDevices.enumerateDevices().then(md => { console.log(md) }); and use field
MediaDeviceInfo.kind Read only
Returns an enumerated value that is either "videoinput", "audioinput" or "audiooutput".
and
MediaDeviceInfo.groupId Read only
Returns a DOMString that is a group identifier. Two devices have the same group identifier if they belong to the same physical device β for example a monitor with both a built-in camera and a microphone.
That is, if several "videoinput" and their groupId are the same, most likely this is a mobile device, since there are more than one laptop and monitor with two cameras and more.
That function suported all desktop and mobile browsers except IE.
Great! An alternative solution. Thanks!
User Agent detection is not a recommended technique for modern web apps. There is a JavaScript API built-in for detecting media. The JavaScript window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string. You can use this method to detect a mobile device based on the CSS media query.
$(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.");
}
});
You can use above script to do show/hide elements depending on the screen size.
net-informations.com/js/progs/mobi...
'ontouchstart' in window
=> true for mobile devices
=> false for desktop environment
Some desktops have touchscreen devices, this is not reliable
I think you've taken the question too literally. The main issue behind the question is for developers to distinguish whether their JavaScript code needs to handle touch events vs click events, and not to figure out if someone can literally lug their device around in a mobile manner. Determining if touch events are in the window object is a simple way to determine this. Cheers!
No, this is very often not true.
In my case, I'm interested in this right now because I need to default the UI rendering of a webpage to relate better to our mobile app when the user is on mobile.
If the user lands on a marketing page, for example, we want to frontload the marketing copy that talks about the mobile features of our product suite. That's not relevant to someone running Windows on a touchscreen laptop.
This is working fine! Thank you.
Great! I hope this could help who need to detect if browser on a mobile device.
Thanks for your visiting.
it's better to use 'navigator.userAgentData.mobile' because it only returns true or false
unfortunately this property is not supported all browsers
developer.mozilla.org/en-US/docs/W...
an interesting solution for new browsers, and most importantly fast:
stackoverflow.com/questions/783868...?
a pity that display media-queries are not available for very ancient devices and browsers (hello Safari)
for server side detect device in production, i use packet npmjs.com/package/node-device-dete... (I'm the author, maybe I'm PR late)
Thank you!
I have made some improvements to the speed of detecting devices and clients, if you also use the library, I recommend updating the dependency to the latest version.
Great! Thank you!
It worked very well for me. Thanks, @timhuang
I adapted the modification proposed by @drgaud