I’m trying to create a simple function that returns a boolean indicating whether the user is on a mobile browser. While I know I can use navigator.userAgent
and regex to match strings, the variety of user-agent formats across devices makes this approach unreliable. I’m hoping there’s a more complete javascript detect mobile
solution that already handles this effectively.
Hey, I’ve done a fair bit of lightweight front-end work, and for small projects, you really can get by with a simple navigator.userAgent
regex check.
function isMobileDevice() {
return /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
console.log(isMobileDevice()); // true or false
Why I use this: When I was hacking together a landing page that just needed a few
javascript detect mobile
tweaks (like hiding some animations on phones), this quick snippet was all I needed. No need for heavy libraries or over-engineering — just match the known strings and move on.
I’ve worked more on PWAs and modern apps, and while regex works, I’ve seen it break or give false positives. That’s where navigator.userAgentData
comes in — it’s a cleaner, more robust option for modern browsers.
function isMobileDevice() {
return navigator.userAgentData ? navigator.userAgentData.mobile : /Mobi|Android/i.test(navigator.userAgent);
}
console.log(isMobileDevice()); // true or false
Why I like this: For
javascript detect mobile
use cases where you need something future-proof (like adapting a web app’s UI smoothly), this hybrid approach is great — it checks the modern API first and falls back to regex only if needed. I used this on a PWA project where consistency across devices really mattered.
With about five years in front-end-heavy projects, I’ve learned that sometimes, it’s not about the device — it’s about the actual environment. You might want to know: is the screen small? Does it support coarse touch (like fingers)?
function isMobileDevice() {
return window.matchMedia("(pointer: coarse)").matches && window.innerWidth <= 768;
}
console.log(isMobileDevice()); // true or false
When this helped me: I was working on a game where the experience had to adjust based on input style, not device brand. This
javascript detect mobile
approach let me tailor the UI based on the real conditions: small screens, touch interfaces — not just labels like “iPhone” or “Android.”