DEV Community

Timothy Huang
Timothy Huang

Posted on

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

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 (17)

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.

Thread Thread
karlsnyder0 profile image
Karl Snyder • Edited on

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

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
timhuang profile image
Timothy Huang Author

thanks for your improvement! :)

Collapse
oskarcodes profile image
Oskar Codes

Make it shorter like this:

function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
timhuang profile image
Timothy Huang Author

Thank you!

Collapse
andreseduardop profile image
andreseduardop

It worked very well for me. Thanks, @timhuang
I adapted the modification proposed by @drgaud

function 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
Collapse
talha_rafiquee profile image
Talha Rafique πŸ‘¨β€πŸ’»

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

Collapse
linehammer profile image
linehammer

You can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query.

if (window.matchMedia("(max-width: 767px)").matches)
{
// The viewport is less than 768 pixels wide
document.write("This is a mobile device.");
}

You may also use navigator.userAgentData.mobile .

const isMobile = navigator.userAgentData.mobile;

Another approach would be a responsive media query. You could presume that a mobile phone has a screen size greater than x and less than y. For example:

@media only screen and (min-width: 320px) and (max-width: 600px) {}

net-informations.com/js/iq/default...

Collapse
kak_kotyavo profile image
KAK KOTYAVO!

an interesting solution for new browsers, and most importantly fast:
stackoverflow.com/questions/783868...?

a pity that display media-queries are not available for very ancient devices and browsers (hello Safari)

for server side detect device in production, i use packet npmjs.com/package/node-device-dete... (I'm the author, maybe I'm PR late)

Collapse
mk1331 profile image
MK1331 • Edited on

Alternatively, you can use

navigator.mediaDevices.enumerateDevices().then(md => { console.log(md) }); and use field

MediaDeviceInfo.kind Read only
Returns an enumerated value that is either "videoinput", "audioinput" or "audiooutput".

and

MediaDeviceInfo.groupId Read only
Returns a DOMString that is a group identifier. Two devices have the same group identifier if they belong to the same physical device β€” for example a monitor with both a built-in camera and a microphone.

That is, if several "videoinput" and their groupId are the same, most likely this is a mobile device, since there are more than one laptop and monitor with two cameras and more.

That function suported all desktop and mobile browsers except IE.

Collapse
linehammer profile image
linehammer

User Agent detection is not a recommended technique for modern web apps. There is a JavaScript API built-in for detecting media. The JavaScript window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string. You can use this method to detect a mobile device based on the CSS media query.

$(document).ready(function(){
let isMobileDevice = window.matchMedia("only screen and (max-width: 760px)").matches;
if(isMobileDevice){
// The viewport is less than 768 pixels wide
//Conditional script here
} else{
//The viewport is greater than 700 pixels wide
alert("This is not a mobile device.");
}
});

You can use above script to do show/hide elements depending on the screen size.

net-informations.com/js/progs/mobi...

Collapse
mehedilslamripon profile image
Mehedi Islam Ripon

This is working fine! Thank you.