如何使用 JavaScript 检测移动设备?

我被要求创建一个实际的 HTML 页面/JavaScript 来模拟使用 JavaScript 代码检测移动设备(iPhone/iPad/Android)。然后,这将把用户带到一个不同的屏幕,要求他们的电子邮件地址。

211805 次浏览

A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:

if( screen.width <= 480 ) {
location.href = '/mobile.html';
}

The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.

The only exception here are tablet pc's like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.

Determine what the User Agent is for the devices that you need to simulate and then test a variable against that.

for example:

// var userAgent = navigator.userAgent.toLowerCase(); // this would actually get the user agent


var userAgent = "iphone"; /* Simulates User Agent for iPhone */
if (userAgent.indexOf('iphone') != -1) {
// some code here
}

You would detect the requesting browsers user agent string, and then decide based on what it is if it's coming from a mobile browser or not. This device is not perfect, and never will be due to the fact that user agents aren't standardized for mobile devices (at least not to my knowledge).

This site will help you create the code: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm

Example:

You could get the user agent in javascript by doing this:

var uagent = navigator.userAgent.toLowerCase();

And then do the check's in the same format as this (just using iPhone as a quick example, but others would need to be a little bit different)

function DetectIphone()
{
if (uagent.search("iphone") > -1)
alert('true');
else
alert('false');
}

Edit

You'd create a simple HTML page like so:

<html>
<head>
<title>Mobile Detection</title>
</head>
<body>
<input type="button" OnClick="DetectIphone()" value="Am I an Iphone?" />
</body>
</html>
<script>
function DetectIphone()
{
var uagent = navigator.userAgent.toLowerCase();
if (uagent.search("iphone") > -1)
alert('true');
else
alert('false');
}
</script>

You can use the user-agent string to detect this.

var useragent = navigator.userAgent.toLowerCase();


if( useragent.search("iphone") )
; // iphone
else if( useragent.search("ipod") )
; // ipod
else if( useragent.search("android") )
; // android
etc

You can find a list of useragent strings here http://www.useragentstring.com/pages/useragentstring.php

var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null
|| screen.width <= 480;

A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is

@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px)  {
#hoofdcollumn {margin: 10px 5%; width:90%}
}

Hope this helps!

if(navigator.userAgent.match(/iPad/i)){
//code for iPad here
}


if(navigator.userAgent.match(/iPhone/i)){
//code for iPhone here
}




if(navigator.userAgent.match(/Android/i)){
//code for Android here
}






if(navigator.userAgent.match(/BlackBerry/i)){
//code for BlackBerry here
}




if(navigator.userAgent.match(/webOS/i)){
//code for webOS here
}

This is my version, quite similar to the upper one, but I think good for reference.

if (mob_url == "") {
lt_url = desk_url;
} else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") {
lt_url = mob_url;
} else {
lt_url = desk_url;
}

I advise you check out http://wurfl.io/

In a nutshell, if you import a tiny JS file:

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>

you will be left with a JSON object that looks like:

{
"complete_device_name":"Google Nexus 7",
"is_mobile":true,
"form_factor":"Tablet"
}

(that's assuming you are using a Nexus 7, of course) and you will be able to do things like:

WURFL.complete_device_name

This is what you are looking for.

Disclaimer: I work for the company that offers this free service. Thanks.

I use mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)

Device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser and use $.support instead).

To detect mobile you can check for touch events:

function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
}

Taken from What's the best way to detect a 'touch screen' device using JavaScript?

Simply use DeviceDetection

deviceDetection.deviceType // phone | tablet according to device

I know this answer is coming 3 years late but none of the other answers are indeed 100% correct. If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
// Take the user to a different screen here.
}

So I did this. Thank you all!

<head>
<script type="text/javascript">
function DetectTheThing()
{
var uagent = navigator.userAgent.toLowerCase();
if (uagent.search("iphone") > -1 || uagent.search("ipad") > -1
|| uagent.search("android") > -1 || uagent.search("blackberry") > -1
|| uagent.search("webos") > -1)
window.location.href ="otherindex.html";
}
</script>


</head>


<body onload="DetectTheThing()">
VIEW NORMAL SITE
</body>


</html>

Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):

if (matchMedia('handheld').matches) {
//...
} else {
//...
}

Another possibility is to use mobile-detect.js. Try the demo.

Browser usage:

<script src="mobile-detect.js"></script>
<script>
var md = new MobileDetect(window.navigator.userAgent);
// ... see below
</script>

Node.js / Express:

var MobileDetect = require('mobile-detect'),
md = new MobileDetect(req.headers['user-agent']);
// ... see below

Example:

var md = new MobileDetect(
'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' +
' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' +
' Version/4.0 Mobile Safari/534.30');


// more typically we would instantiate with 'window.navigator.userAgent'
// as user-agent; this string literal is only for better understanding


console.log( md.mobile() );          // 'Sony'
console.log( md.phone() );           // 'Sony'
console.log( md.tablet() );          // null
console.log( md.userAgent() );       // 'Safari'
console.log( md.os() );              // 'AndroidOS'
console.log( md.is('iPhone') );      // false
console.log( md.is('bot') );         // false
console.log( md.version('Webkit') );         // 534.3
console.log( md.versionStr('Build') );       // '4.1.A.0.562'
console.log( md.match('playstation|xbox') ); // false

This is an example of how to check if webpage is loaded in Desktop or mobile app.

JS will execute on page load and you can do Desktop specific things on page load eg hide barcode scanner.

   <!DOCTYPE html>
<html>
<head>
<script type="text/javascript">


/*
* Hide Scan button if Page is loaded in Desktop Browser
*/
function hideScanButtonForDesktop() {


if (!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))) {


// Hide scan button for Desktop
document.getElementById('btnLinkModelScan').style.display = "none";
}
}


//toggle scanButton for Desktop on page load
window.onload = hideScanButtonForDesktop;
</script>
</head>

As I (kind of without success) searched for the proper solution for my hack, I want to add my hack here nonetheless: I simply check for support of device orientation, which seems the most significant diffrence between mobiles and desktop:

var is_handheld=0; // just a global if(window.DeviceOrientationEvent) {is_handheld=1;}

That being said, imho a page should also offer manual choice between mobile / desktop layout. I got 1920*1080 and I can zoom in - an oversimplified and feature-reduced wordpressoid chunk is not always a good thing. Especially forcing a layout based on nonworking device detection - it happens all the time.

Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:

let isMouseAvailable = window.matchMedia("(any-pointer:coarse)").matches;

That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.

The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.

https://patrickhlauke.github.io/touch/touchscreen-detection/

Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia

In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.

Similar to several of the answers above. This simple function, works very well for me. It is current as of 2019

function IsMobileCard()
{
var check =  false;


(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);


return check;
}

The cleanest way of finding device type is:

if (navigator.userAgentData.mobile) { // do something }

(although it isn't yet supported on Safari)

More info: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/mobile