HTML5: Detecting if you’re on mobile or pc with javascript? [duplicate]

I was looking into this a few years back. In short, you can’t do this with 100% reliability. There seem to be 2 approaches commonly used to provide a ‘best-guess’:

1. User Agent Detection
This is where you check what the client is claiming to be.
e.g.

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    // is mobile..
}

It’s not perfect, since I believe it is fairly easy for this property to be altered accidentally or otherwise. Plus it is highly unlikely that this list will still be accurate in 2 years’ / 2 weeks’ / 2 days’ time!

2. Using Client Capabilities
As you can imagine, a more pragmatic approach – allows you to cater to the known physical capability of the client. e.g.

if( screen.width <= 480 ) {     
    // is mobile.. 
}

However this is not ideal either, since higher and higher pixel densities in modern devices give you a misleading result: appearing that you have more ‘room’ than you actually do. Plus different browsers may expose their capabilities through different means.

If anyone has any better ideas to robustly discern between desktop and device, please comment! 🙂

Leave a Comment