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");
}
Enter fullscreen mode Exit fullscreen mode

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

Latest comments (34)

Collapse
 
tntsimr profile image
tnt sim

I am using a mobile and when I open the TNT Sim registration official URL then my mobile creates different issues.

Collapse
 
tgregoneil profile image
T. Greg O'Neil

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

Collapse
 
jdvivar profile image
Daniel Vivar

Some desktops have touchscreen devices, this is not reliable

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

Thread 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.

Collapse
 
pro2stinger profile image
Pro2stinger • Edited

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

Collapse
 
ruslanstelmakh profile image
ruslanstelmakh

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

Collapse
 
mehedilslamripon profile image
Mehedi Islam Ripon

This is working fine! Thank you.

Collapse
 
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.

Collapse
 
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.

Collapse
 
timhuang profile image
Timothy Huang

Great! An alternative solution. Thanks!

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
 
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
 
kouba profile image
Martin Kouba

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

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

Collapse
 
timhuang profile image
Timothy Huang

Thanks for sharing!

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

Thank you!

Collapse
 
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.

Thread Thread
 
timhuang profile image
Timothy Huang

Great! Thank you!

Collapse
 
talha_rafiquee profile image
Talha Rafique 👨‍💻

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