DEV Community

loading...

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

Discussion

pic
Editor guide
Collapse
bechtold profile image
Oskar Bechtold

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

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

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.

Collapse
drgaud profile image
DrGaud

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: 
        // https://dev.to/timhuang/a-simple-way-to-detect-if-browser-is-on-a-mobile-device-with-javascript-44j3
        if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
            return true
       }
       else{
            return false
       }
    } 
Enter fullscreen mode Exit fullscreen mode

Honestly thanks for this eloquent regex test.

Collapse
talha_rafiquee profile image
Talha Rafique 👨‍💻

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