检测桌面与移动浏览器的可靠方法

moe*_*oey 11 javascript php cross-browser browser-detection

可能重复:
在Javascript中进行浏览器检测的最佳方法是什么?

我想基本上做以下(在JavaScript或PHP中):

if (desktop browser) {
     do x;
}
else {   // mobile browser
     do not do x;
}
Run Code Online (Sandbox Code Playgroud)

众所周知,不推荐使用浏览器检测方法.更好的解决方案是使用功能测试.我的问题是,随着移动浏览器变得更智能,功能与桌面版一样强大,从非桌面浏览器过滤桌面的理想排他性能检测是什么?

我认为扭转条件检查即if (mobile browser) {} else ...可能证明更有问题,对吧?

Rém*_*ton 14

来自A Beautiful Site的 Google搜索结果:

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()){
    // Mobile!
} else {
    // Not mobile
}
Run Code Online (Sandbox Code Playgroud)

我不会说这个功能检测方法最好用户代理嗅探,这是可怕的实际.但是,如果您正在检测功能以确定该设备是否被视为移动设备,那么您将面临一系列新问题.

您无法检查,pixel-ratio因为新桌面计算机很可能是"视网膜"或超高清.您无法检查,device-orientation因为它不再是手机独有的东西.您无法检查(如果可以)陀螺仪,因为某些笔记本电脑可能会返回值.

构建适用于所有平台的网站,而不是试图将它们分开!