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");
}
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung

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

Top comments (35)

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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 :-)

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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 ;-)

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung Thread
 
karlsnyder0 profile image
Karl Snyder • • Edited

"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!

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 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.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 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.)

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung Thread
 
gabrielmlinassi profile image
Gabriel Linassi •

@jeancarlo13 the problem with using media queries in JS is that it causes layout shift (FOUC) and it's a problem mainly on above-the-fold UI. Otherwise it's a good approach.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
burakdev profile image
Burak Bilen • • Edited

`export function useMediaQuery(query) {
const subscribe = React.useCallback(
(callback) => {
const matchMedia = window.matchMedia(query);

  matchMedia.addEventListener("change", callback);

  return () => {
    matchMedia.removeEventListener("change", callback);
  };
},
[query]
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung

);

const getSnapshot = () => {
return window.matchMedia(query).matches;
};

const getServerSnapshot = () => {
throw Error("useMediaQuery is a client-only hook");
};

return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}`

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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...

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
timhuang profile image
Timothy Huang •

Thanks for sharing!

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
kouba profile image
Martin Kouba •

Unfortunately navigator.userAgentData.mobile appears to be not widely supported yet

caniuse.com/?search=userAgentData
caniuse.com/?search=mobile

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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
       }
    } 
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung

Honestly thanks for this eloquent regex test.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
timhuang profile image
Timothy Huang •

thanks for your improvement! :)

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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);
}
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung Thread
 
timhuang profile image
Timothy Huang •

Thank you!

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung Thread
 
mitya profile image
Dima • • Edited
const isMobile = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung Thread
 
timhuang profile image
Timothy Huang •

Wow, really short! Thanks for your improvement.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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
   };
};
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung 🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
mk1331 profile image
MK1331 • • Edited

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.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
timhuang profile image
Timothy Huang •

Great! An alternative solution. Thanks!

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
tgregoneil profile image
T. Greg O'Neil •

'ontouchstart' in window
=> true for mobile devices
=> false for desktop environment

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
jdvivar profile image
Daniel Vivar •

Some desktops have touchscreen devices, this is not reliable

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
tgregoneil profile image
T. Greg O'Neil •

I think you've taken the question too literally. The main issue behind the question is for developers to distinguish whether their JavaScript code needs to handle touch events vs click events, and not to figure out if someone can literally lug their device around in a mobile manner. Determining if touch events are in the window object is a simple way to determine this. Cheers!

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung Thread
 
pursechartthere profile image
Some Dev • • Edited

I think you've taken the question too literally. The main issue behind the question is for developers to distinguish whether their JavaScript code needs to handle touch events vs click events

No, this is very often not true.

In my case, I'm interested in this right now because I need to default the UI rendering of a webpage to relate better to our mobile app when the user is on mobile.

If the user lands on a marketing page, for example, we want to frontload the marketing copy that talks about the mobile features of our product suite. That's not relevant to someone running Windows on a touchscreen laptop.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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...

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
mehedilslamripon profile image
Mehedi Islam Ripon •

This is working fine! Thank you.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
timhuang profile image
Timothy Huang •

Great! I hope this could help who need to detect if browser on a mobile device.
Thanks for your visiting.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
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)

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
timhuang profile image
Timothy Huang •

Thank you!

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
kak_kotyavo profile image
KAK KOTYAVO! •

I have made some improvements to the speed of detecting devices and clients, if you also use the library, I recommend updating the dependency to the latest version.

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung Thread
 
timhuang profile image
Timothy Huang •

Great! Thank you!

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
pro2stinger profile image
Pro2stinger • • Edited

it's better to use 'navigator.userAgentData.mobile' because it only returns true or false

🔥 Jadwal & Hasil: timhuang/a simple way to detect if browser is on a mobile device with javascript j - Jadwal Siaran Langsung
 
ruslanstelmakh profile image
ruslanstelmakh •

unfortunately this property is not supported all browsers
developer.mozilla.org/en-US/docs/W...