检测移动设备的最佳方法是什么?

JavaScript

ANear

2020-03-09

有没有可靠的方法来检测用户是否在jQuery中使用移动设备?类似于CSS @media属性吗?如果浏览器在手持设备上,我想运行其他脚本。

jQuery $.browser函数不是我想要的。

第242篇《检测移动设备的最佳方法是什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

19个回答
古一L 2020.03.09

不应单独信任用户代理字符串。以下解决方案将在所有情况下均适用。

function isMobile(a) {
  return (/(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)));
}

并调用此函数:

isMobile(navigator.userAgent || navigator.vendor || window.opera)
飞云逆天 2020.03.09

我用这个

if(navigator.userAgent.search("mobile")>0 ){
         do something here
}
神无前端Jim 2020.03.09

怎么样mobiledetect.net

其他解决方案似乎太基础了。这是一个轻量级的PHP类。它结合使用User-Agent字符串和特定的HTTP标头来检测移动环境。您还可以通过使用以下任何第三方插件来从Mobile Detect中受益:WordPress,Drupal,Joomla,Magento等。

米亚Sam 2020.03.09
<script>
  function checkIsMobile(){
      if(navigator.userAgent.indexOf("Mobile") > 0){
        return true;
      }else{
        return false;
      }
   }
</script>

如果您使用任何浏览器,并且尝试获取navigator.userAgent,那么我们将获得以下浏览器信息:

Mozilla / 5.0(Macintosh;英特尔Mac OS X 10_13_1)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 64.0.3282.186 Safari / 537.36

如果您在移动设备上做同样的事情,那么您将得到关注

Mozilla / 5.0(Linux; Android 8.1.0; Pixel Build / OPP6.171019.012)AppleWebKit / 537.36(KHTML,如Gecko)Chrome / 61.0.3163.98 Mobile Safari / 537.36

每个移动浏览器都有一个带“ Mobile”字符串的useragent,因此我在代码中使用上面的代码段检查当前用户代理是否为web / mobile。根据结果​​,我将进行必要的更改。

乐Eva 2020.03.09

您可以使用媒体查询来轻松处理它。

isMobile = function(){
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");
    return isMobile.matches ? true : false
}
斯丁Near 2020.03.09

基于http://detectmobilebrowser.com/的简单功能

function isMobile() {
    var a = navigator.userAgent||navigator.vendor||window.opera;
    return /(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|phone)|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));
}
米亚Sam 2020.03.09

我建议使用以下字符串组合,以检查是否使用了设备类型。

根据Mozilla文档字符串Mobi的建议。但是,某些旧的数位板仅Mobi使用时不会返回true ,因此我们也应该使用Tablet字符串。

同样,出于安全考虑iPadiPhone字符串也可用于检查设备类型。

大多数新设备将返回trueMobi单独的字符串。

if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
    // do something
}
神无阳光 2020.03.09

如果发现仅仅检查navigator.userAgent并不总是可靠的。也可以通过检查来提高可靠性navigator.platform对先前答案的简单修改似乎更好:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
   (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
    // some code...
}
番长斯丁Itachi 2020.03.09

很好的回答,谢谢。支持Windows Phone和Zune的小改进:

if (navigator.userAgent.match(/Android/i) ||
  navigator.userAgent.match(/webOS/i) ||
  navigator.userAgent.match(/iPhone/i) ||
  navigator.userAgent.match(/iPad/i) ||
  navigator.userAgent.match(/iPod/i) ||
  navigator.userAgent.match(/BlackBerry/) ||
  navigator.userAgent.match(/Windows Phone/i) ||
  navigator.userAgent.match(/ZuneWP7/i)
) {
  // some code
  self.location = "top.htm";
}
FOUR 2020.03.09

您不能依靠navigator.userAgent,不是每个设备都能显示其真实的操作系统。例如,在我的HTC上,它取决于设置(“使用移动版本”打开/关闭)。http://my.clockodo.com上,我们只是用来screen.width检测小型设备。不幸的是,在某些Android版本中,screen.width存在一个错误。您可以将这种方式与userAgent结合使用:

if(screen.width < 500 ||
 navigator.userAgent.match(/Android/i) ||
 navigator.userAgent.match(/webOS/i) ||
 navigator.userAgent.match(/iPhone/i) ||
 navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
}
伽罗L 2020.03.09

令我惊讶的是,没有人指出一个不错的网站:http : //detectmobilebrowsers.com/它已经提供了用于移动检测的各种语言的现成代码(包括但不限于):

  • 阿帕奇
  • 均价
  • C#
  • IIS
  • 的JavaScript
  • NGINX
  • 的PHP
  • 佩尔
  • 蟒蛇
  • 滑轨

并且,如果您还需要检测平板电脑,只需检查About部分中的其他RegEx参数即可。

设计时未检测到Android平板电脑,iPad,Kindle Fires和PlayBooks。要添加对平板电脑的支持,请添加|android|ipad|playbook|silk到第一个正则表达式。

ProTony 2020.03.09

如果您不特别担心小型显示器,可以使用宽度/高度检测。这样,如果宽度小于一定大小,则会抛出移动站点。这可能不是完美的方法,但是可能很容易检测到多个设备。您可能需要为iPhone 4(大尺寸)放入特定的手机。

Tom凯飞云 2020.03.09

我知道这个问题有很多答案,但是据我所知,没有人以解决这个问题的方式来回答这个问题。

CSS使用width(媒体查询)来确定基于width应用于Web文档的样式。为什么不在JavaScript中使用width?

例如,在Bootstrap(移动优先)的媒体查询中,存在4个捕捉/断点:

  • 超小型设备为768像素及以下。
  • 小型设备的范围从768到991像素。
  • 中型设备范围从992到1199像素。
  • 大型设备为1200像素及以上。

我们也可以使用它来解决我们的JavaScript问题。

首先,我们将创建一个函数,该函数获取窗口大小并返回一个值,该值使我们能够查看设备正在查看应用程序的大小:

var getBrowserWidth = function(){
    if(window.innerWidth < 768){
        // Extra Small Device
        return "xs";
    } else if(window.innerWidth < 991){
        // Small Device
        return "sm"
    } else if(window.innerWidth < 1199){
        // Medium Device
        return "md"
    } else {
        // Large Device
        return "lg"
    }
};

现在我们已经设置了函数,我们可以将其称为ans存储值:

var device = getBrowserWidth();

你的问题是

I would like to run a different script if the browser is on a handheld device.

Now that we have the device information all that is left is an if statement:

if(device === "xs"){
  // Enter your script for handheld devices here 
}

Here is an example on CodePen: http://codepen.io/jacob-king/pen/jWEeWG

米亚神奇 2020.03.09

在以下位置找到了解决方案:http : //www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

然后,要验证其是否为移动设备,可以使用以下方法进行测试:

if(isMobile.any()) {
   //some code...
}
SamEva 2020.03.09

如果用“移动”表示“小屏幕”,则使用以下代码:

var windowWidth = window.screen.width < window.outerWidth ?
                  window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;

在iPhone上,您的window.screen.width最终为320。在Android上,您的window.outerWidth最终为480(尽管这可能取决于Android)。iPad和Android平板电脑将返回768之类的数字,因此它们将获得所需的完整视图。

阳光阿飞 2020.03.09

编者注:对于现代Web应用程序,不建议使用用户代理检测技术。请参阅此答案下方的评论以确认这一事实。建议使用特征检测和/或媒体查询来使用其他答案之一。


除了使用jQuery,您还可以使用简单的JavaScript进行检测:

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

或者,您也可以将两者结合使用,以使其更易于通过jQuery访问...

$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));

现在$.browser将为"device"以上所有设备返回

注意:$.browser已在jQuery v1.9.1删除但是您可以通过使用jQuery迁移插件代码来使用它


更全面的版本:

var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|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|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /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(navigator.userAgent.substr(0,4))) { 
    isMobile = true;
}
村村伽罗Mandy 2020.03.09

According to Mozilla - Browser detection using the user agent:

In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.

Like this:

if (/Mobi/.test(navigator.userAgent)) {
    // mobile!
}

This will match all common mobile browser user agents, including mobile Mozilla, Safari, IE, Opera, Chrome, etc.

Update for Android

EricL recommends testing for Android as a user agent also, as the Chrome user agent string for tablets does not include "Mobi" (the phone versions do however):

if (/Mobi|Android/i.test(navigator.userAgent)) {
    // mobile!
}
Mandy猴子阿飞 2020.03.09

它不是jQuery,但我发现了这一点:http : //detectmobilebrowser.com/

它提供了脚本来检测多种语言的移动浏览器,其中一种是JavaScript。这可能会帮助您找到想要的东西。

但是,由于您使用的是jQuery,因此您可能希望了解jQuery.support集合。它是用于检测当前浏览器功能的属性的集合。文档在这里:http : //api.jquery.com/jQuery.support/

由于我不知道您到底要完成什么,因此我不知道其中哪一个最有用。

话虽如此,我认为您最好的选择是使用服务器端语言(如果可以的话)重定向或编写不同的脚本到输出。由于您实际上并不了解移动浏览器x的功能,因此在服务器端进行检测和更改逻辑将是最可靠的方法。当然,如果您不能使用服务器端语言,那么所有这些都是有争议的:)

猴子小小Tony 2020.03.09

您想要检测移动设备所做的工作与IMO的“浏览器嗅探”概念有点过近了。进行某些功能检测可能会更好。http://www.modernizr.com/这样的库可以提供帮助。

例如,移动和非移动之间的界线在哪里?每天变得越来越模糊。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android