DEV Community


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

timhuang profile image Timothy Huang ・1 min read

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");
  // false for not mobile device
  document.write("not mobile device");

demo is on codepen:



Editor guide
bechtold profile image
Oskar Bechtold

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:
Hope that helps :-)

angelbearuk profile image
Kristy Whalen

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 ;-)

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.

drgaud profile image

Thank you for this,
I have ended up placing it in a view class as a getter function

get isMobile(){
        // credit to Timothy Huang for this regex test: 
        if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
            return true
            return false
Enter fullscreen mode Exit fullscreen mode

Honestly thanks for this eloquent regex test.

talha_rafiquee profile image
Talha Rafique 👨‍💻

thank man,
it helped me a lot. working like a charm.