可靠的方式来检测桌面与移动浏览器 [英] Reliable Way to Detect Desktop vs. Mobile Browser
问题描述
我想基本上执行以下操作(在JavaScript或PHP中):
I'd like to essentially do the following (in JavaScript or PHP):
if (desktop browser) {
do x;
}
else { // mobile browser
do not do x;
}
已知使用浏览器不建议使用检测方法。更好的解决方案是使用能力测试。我的问题是,使用移动浏览器变得更聪明,与桌面版本一样强大,什么是独特的能力检测来从非桌面浏览器过滤桌面?
It is known that using a browser detection method is not recommended. A better solution is using a capability testing. My question is, with mobile browsers become smarter and as powerful as the desktop version, what ideally exclusive capability detection to filter the desktop from non-desktop browsers?
条件检查, if(mobile browser){} else ...
可能被证明是更有问题,对吗?
I think reversing the conditional check i.e. if (mobile browser) {} else ...
might prove to be more problematic, right?
推荐答案
What a little Google search turned up, from A Beautiful Site:
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
}
I不会认为特征检测优于用户代理嗅探,这实际上是可怕的。但是,如果您要检测功能以确定设备是否被视为移动设备,那么您将面临一系列全新的问题。
I will not argue that feature detection is way preferable to user-agent sniffing, which is terrible actually. But if you're detecting feature to determine whether or not the device is considered mobile or not, you're exposing yourself to a whole new serie of problems.
您可以不要检查 pixel-ratio
,因为新的台式电脑很可能是retina或超高清。您不能检查设备导向
,因为它不再是手机独有的东西。
You can't check pixel-ratio
because new desktops computers will most likely be "retina" or super-HD. You can't check device-orientation
because it's not something unique to mobiles anymore. You can't check (if you can) the gyroscope because some laptop might return values.
建立可在所有平台上使用的网站,而不必试图将它们分开!
Build websites that works on all platforms without trying to separate them!
这篇关于可靠的方式来检测桌面与移动浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!