Detecting iOS / Android Operating system

Alexander Lozada picture Alexander Lozada · Feb 13, 2014 · Viewed 231.9k times · Source

I've done some research, and this question has come up, but not in the way I intend. I'm building a page for a client that is a QR code landing, which is a place to download an application. So he doesn't have to print out 2 QR codes on a page, I'd like to detect the current operating system (Apple/Android/Other[not supported]) and modify my elements based on that value.

I've looked at the script "detectmobilebrowsers" and that is just aimed at telling whether or not the user is mobile at all, whereas I would like to figure out what operating system the user is running and suggest the best application version.

Other answers I found similar to this question seemed either outdated or unreliable (has no detection for Android tablet browsers), so I'm in search of something new. How can I achieve this? (Preferably using jQuery - Javascript - PHP in that order).

Answer

feeela picture feeela · Feb 13, 2014

You can test the user agent string:

/**
 * Determine the mobile operating system.
 * This function returns one of 'iOS', 'Android', 'Windows Phone', or 'unknown'.
 *
 * @returns {String}
 */
function getMobileOperatingSystem() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

      // Windows Phone must come first because its UA also contains "Android"
    if (/windows phone/i.test(userAgent)) {
        return "Windows Phone";
    }

    if (/android/i.test(userAgent)) {
        return "Android";
    }

    // iOS detection from: http://stackoverflow.com/a/9039885/177710
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "iOS";
    }

    return "unknown";
}