DEV Community

Discussion on: A simple way to detect if browser is on a mobile device with Javascript

Collapse
 
bechtold profile image
Oskar Bechtold

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.

Thread Thread
 
karlsnyder0 profile image
Karl Snyder • Edited

"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!

Thread Thread
 
jeancarlo13 profile image
Jean Carlo 13

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.

Thread Thread
 
karlsnyder0 profile image
Karl Snyder

"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.)

Thread Thread
 
gabrielmlinassi profile image
Gabriel Linassi

@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.