Reliable Way to Detect Desktop vs. Mobile Browser

moey picture moey · Jan 21, 2013 · Viewed 24.1k times · Source

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?

Answer

Rémi Breton picture Rémi Breton · Jan 21, 2013

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!