Reliable Way to Detect Desktop vs. Mobile Browser [duplicate]

天大地大妈咪最大 提交于 2019-12-28 11:46:46

问题


Possible Duplicate:
What is the Best way to do Browser Detection in Javascript?

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?

I think reversing the conditional check i.e. if (mobile browser) {} else ... might prove to be more problematic, right?


回答1:


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 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.

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!




回答2:


I think you're looking for the get_browser() function in php.

Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.



来源:https://stackoverflow.com/questions/14440296/reliable-way-to-detect-desktop-vs-mobile-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!