我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。

我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。

我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。


当前回答

特征检测

const isMobile = localStorage.mobile || window.navigator.maxTouchPoints > 1;

截至2022-02-07,工作在CHROME + SAFARI::结合功能检测并尝试本线程和其他网站中的所有内容。localStorage。移动工作在Chrome移动;后者适用于Safari移动版。在打开或不打开dev-tools时和/或在移动模拟器上不会触发桌面浏览器。在撰写本文时,它会触发一个真正的移动浏览器,而不是桌面。

请考虑

我还在Win10上的联想X1 Yoga(键盘模式或平板模式)上进行了测试

localStorage。无论如何,移动是没有定义的 当笔记本电脑处于键盘模式时:window.navigator。maxTouchPoints is 1→isMobile为false 当键盘向后翻转,笔记本电脑处于平板电脑模式时:window.navigator。maxTouchPoints是10→isMobile是true

其他回答

IE10+解决方案仅使用matchMedia:

const isMobile = () => window.matchMedia('(max-width: 700px)').matches

isMobile()返回布尔值

这是一个比匹配更有效的userAgent解决方案…

function _isMobile(){
    // if we want a more complete list use this: http://detectmobilebrowsers.com/
    // str.test() is more efficent than str.match()
    // remember str.test is case sensitive
    var isMobile = (/iphone|ipod|android|ie|blackberry|fennec/).test
         (navigator.userAgent.toLowerCase());
    return isMobile;
}

根据MDN关于使用用户代理进行浏览器检测的文章,建议尽可能避免这种方法,并建议使用其他方法,如特征检测。

然而,如果必须使用用户代理作为检测设备是否移动的手段,他们建议:

总而言之,我们建议在中的任何地方查找字符串“Mobi” 用户代理检测移动设备。

因此,这一行代码就足够了:

const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");

(更新):

正如@ zenwolf在评论中建议的那样,使用正则表达式会更好:

const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)

为了增加额外的控制层,我使用HTML5存储来检测它是使用移动存储还是桌面存储。如果浏览器不支持存储,我有一个移动浏览器名称数组,并将用户代理与数组中的浏览器进行比较。

这很简单。函数如下:

// Used to detect whether the users browser is an mobile browser
function isMobile() {
    ///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
    ///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>

    if (sessionStorage.desktop) // desktop storage 
        return false;
    else if (localStorage.mobile) // mobile storage
        return true;

    // alternative
    var mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile']; 
    for (var i in mobile) if (navigator.userAgent.toLowerCase().indexOf(mobile[i].toLowerCase()) > 0) return true;

    // nothing found.. assume desktop
    return false;
}

检测手机或平板设备的一个好方法是查看浏览器是否可以创建触摸事件。

简单JavaScript代码:

function isMobile() {
   try{ document.createEvent("TouchEvent"); return true; }
   catch(e){ return false; }
}

if (isMobile()) {
   # do whatever you wanna do!
}

这对我来说效果很好,但是包含触摸屏的笔记本电脑设备可能会有一个问题。

我不确定触屏笔记本电脑是否会被视为移动设备,因为我还没有测试过。