简体   繁体   中英

Easiest way to determine if user is on mobile device

I'm showing a notification bar on my website, and frankly, it doesn't work well when its on a mobile device. I'd like to show the bar ONLY for desktop users.

What is the easiest way to determine if a user is on desktop or on mobile?

Check this http://detectmobilebrowsers.com/

Work for Javascript, jQuery etc.

A user agent check is the "easiest", though you could easily employ CSS3 media queries

Here is an example that checks iphone, android and blackberry; you could easily add other mobile browsers.

var is_mobile = !!navigator.userAgent.match(/iphone|android|blackberry/ig) || false;

I find that it's best to use feature detection. Use Modernizr to detect if it's a touch device. You can do things like:

var mousedown = 'mousedown';

if (Modernizr.touch) {
    mousedown = 'touchstart';
}

$('.foo').on(mousedown, handleMouseDown);

And then use CSS Media Queries for handling screen width (and it's also easy to detect screen width with javascript). That way you can correctly handle touch devices with large screens, or non-touch devices with small screens.

If you use modernizr . a "no-touch" class will be added to the element. You could hide the bar by default and add a css rule to show the bar if the "no-touch" class exists. Example:

default:

.bar{display:none;}

desktop:

.no-touch .bar{display:block;}

If the user is on a mobile device this javascript 'if' will return true.

if (navigator.userAgent.indexOf('Mobile') !== -1) { ...

See also: https://deviceatlas.com/blog/list-of-user-agent-strings

The easiest way to differentiate between touch and non-touch devices is using media queries.

1) CSS to target Mobile/Touch Devices can be written using media query,

  @media (hover: none), (pointer: coarse) {}

2) CSS to target Desktop/Non-Touch Devices (only) can be written using media query,

  @media not all and (pointer: coarse) {}

On Few latest mobile devices (Eg: IOS 10+, one plus etc.,.) hover is detected hence we use, the (2) to identify non-touch devices.

 const is_mobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/BlackBerry/i);

if (is_mobile != null){
    popup.modal('show');
}

If you are reading this post 2021, there is an even easier way to find this out.

let isMobile = window.navigator.userAgentData.mobile;
console.log(isMobile);

The above method simply returns a boolean value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM