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

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

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


当前回答

我搜索了Replit的代码(因为它在网站上到处都是错误),直到我看到:

(function (isTouchDevice) {
      if (!isTouchDevice) return;
      var isTouchClass = 'is-touch-device';
      var docElement = document.documentElement;
      docElement.className = docElement.className ? [docElement.className, isTouchClass].join(' ') : isTouchClass;
    })(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);

所以我把它修改成这样:

function isTouchDevice() {
    if (!(("ontouchstart" in window) || (window.DocumentTouch && document instanceof DocumentTouch))) {
        return false
    }
    return true
}

来自不同用户代理的值:

Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML,像壁虎)Chrome/103.0.0.0 Safari/537.36: false Mozilla / 5.0 (Linux;Android 10;小米A2) AppleWebKit/537.36 (KHTML,像壁虎)Chrome/105.0.0.0移动Safari/537.36: true

其他回答

正如许多人所说,依赖于用户代理数据的移动目标是有问题的。这同样适用于屏幕大小的计数。

我的方法借鉴了CSS技术来确定界面是否是触摸的:

只使用javascript(所有现代浏览器都支持),媒体查询匹配可以轻松推断设备是否是移动设备。

function isMobile() {
    var match = window.matchMedia || window.msMatchMedia;
    if(match) {
        var mq = match("(pointer:coarse)");
        return mq.matches;
    }
    return false;
}

UserAgent不是100%可靠的。

window.navigator.maxTouchPoints > 1;

这就够了!它排除了浏览器开发控制台中的电话模拟器。这对我来说很重要。

不要使用这种方法作为窗口。朝向现在已弃用!!

function isMobile() {
  return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
};

最好的一定是:

var isMobile = (/Mobile/i.test(navigator.userAgent));

但是就像Yoav Barnea说的…

// Seem legit
var isMobile = ('DeviceOrientationEvent' in window || 'orientation' in window);
// But with my Chrome on windows, DeviceOrientationEvent == fct()
if (/Windows NT|Macintosh|Mac OS X|Linux/i.test(navigator.userAgent)) isMobile = false;
// My android have "linux" too
if (/Mobile/i.test(navigator.userAgent)) isMobile = true;

在这3个测试之后,我希望var isMobile是…好吧

如何:

if (typeof screen.orientation !== 'undefined') { ... }

...因为智能手机通常支持这个属性,而桌面浏览器不支持。在MDN中见。

编辑1:正如@Gajus指出的,窗口。Orientation现在已弃用,不应该使用。

编辑2:您可以使用实验屏幕。Orientation而不是弃用的window.orientation。在MDN中见。

编辑3:从窗口更改。朝向屏幕。朝向