简体   繁体   中英

Detect Mobile PHONE with Javascript or JQuery

I am not interested in Tablets or mobile devices. Just if the user is visiting the page with a phone.

I am not looking for something 100% perfect. But a best effort would be nice. If I show a sms 'a' tag link and you are NOT on a phone... it's not the end of the world but I would like to do the best I can.

Any ideas on how to specifically try to filter out for phones even if it is not 100% perfect?

Thanks

There are perhaps a couple of approaches you could take to this - both would be making massive assumptions and be unreliable at best!

The first 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) {}

I'd improve on that to also check for a height, and find some statistics on common device sizes to put sensible breakpoints in there. You also need to account for device orientation, when a device is landscape orientated it'll be wider than usual.

Your other option is to use the user-agent string. Both Apple and Android devices specifically state if it's a mobile version of the device. On iOS you can look for the phrase 'iphone'. On android you can look for 'mobile safari'. Windows phone, and other devices likely have similar detects, you'd need to use emulators to examine each UA string and then construct a suitable regex.

A final possibility, if you're interested specifically in the device's ability to handle telephone operations might be to run a detect against a telephone number.

Create an element on the page that contains a phone number. In iOS (and likely similarly on other platforms), this will get modified so it has an automatic href added with tel: and then your number. You could draw this element off screen, see if the number gets auto-formatted, and presume a mobile phone if so. I imagine an iPad will also do this, but then an iPad will also allow you to send SMS if you have text message forwarding enabled.

I'd suggest doing it server side if you want to manipulate the view for the end user, however I wrote a small JS library that enables this sort of checking a while back - take a look: https://github.com/dj10dj100/what_browser

Along other things you'll be able to check if the browser is a mobile using js : if(what.device.isMobile() == true){ //Mobile device }

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // some code..
}

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