navigator.userAgent accuses Mozilla in IE

0

What do I do to identify if the browser is IE or Moz .. etc ...?

    
asked by anonymous 31.01.2016 / 20:30

1 answer

2

In general, the userAgent is not reliable for detecting browsers. Countless times in history browsers insert words from others and generate confusion and code that stops working. One of the last examples is windows phone have in your UA like iPhone OS 7_0_3 Mac OS X AppleWebKit that causes windows phone to be detected as iPhone ...

The ideal way is to use feature detection (to detect by functionality) to fix any problems.

Anyway, to answer the question here is the code we use in MooTools when the functionality is accurate.

( original Github code here >) (jsfiddle: link )

function getBrowser(ua, platform) {
    ua = ua.toLowerCase();
    platform = (platform ? platform.toLowerCase() : '');

    // chrome is included in the edge UA, so need to check for edge first,
    // before checking if it's chrome.
    var UA = ua.match(/(edge)[\s\/:]([\w\d\.]+)/);
    if (!UA) {
        UA = ua.match(/(opera|ie|firefox|chrome|trident|crios|version)[\s\/:]([\w\d\.]+)?.*?(safari|(?:rv[\s\/:]|version[\s\/:])([\w\d\.]+)|$)/) || [null, 'unknown', 0];
    }

    if (UA[1] == 'trident') {
        UA[1] = 'ie';
        if (UA[4]) UA[2] = UA[4];
    } else if (UA[1] == 'crios') {
        UA[1] = 'chrome';
    }

    platform = ua.indexOf('windows phone') != -1 ? 'windowsmobile' : ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || ua.match(/mac|win|linux/) || ['other'])[0];
    if (platform == 'win') platform = 'windows';

    return {
        //extend: Function.prototype.extend,
        name: (UA[1] == 'version') ? UA[3] : UA[1],
        version: parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]),
        platform: platform
    };
};
var browser = getBrowser(navigator.userAgent, navigator.platform);
alert(JSON.stringify(browser, null, 4));
    
31.01.2016 / 20:49