1
\$\begingroup\$

Based off of another SO reply by kennebec, I had problems following the code so I rewrote it to give myself a better understanding of what is being accomplished.

I would be very grateful if you could critique it or point out any problems I have caused or could modify to improve it.

Tested with IE8/9/10/11, FF, Chrome, Opera & Safari.

Original JSFiddle link Updated with changes from thriggle JSFiddle link

function getBrowser() {
    var userAgent = navigator.userAgent, 
        matched = userAgent.match(/(chrome|firefox|opera|safari|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
        version,
        browser = { name: '', version: '' };

    // IE Shells; I gaurantee that you will see this with Dell branded OEM IE 11 installs.
    if(/trident/i.test(matched[1])) { 
        version = /\brv[ :]+(\d+)/g.exec(userAgent) || [];        

        return { name: 'Internet Explorer', version: (version[1] || '') };
    }

    // Not Chrome; at first glance this looks like a block for chrome identification, but 
    // its actually Opera.
    if(matched[1] === 'Chrome') {
        version = userAgent.match(/\b(OPR|Edge)\/(\d+)/);

        if(version !== null) {
            return { name: version[1].replace('OPR', 'Opera'), version: version[2] };
        }
    }

    // The rest; Chrome, Safari, etc
    matched = matched[2] ? [matched[1], matched[2]] : [navigator.appName, navigator.appVersion, '-?'];

    if((version = userAgent.match(/version\/(\d+)/i)) !== null) {
        matched.splice(1, 1, version[1]);
    }

    browser.name = (matched[0] !== "") ? matched[0] : "Unknown";
    browser.version = (matched[1] !== "") ? matched[1] : "Unknown"; 

    return browser;
}
\$\endgroup\$
2
\$\begingroup\$

Like Kennebec's original answer, the code is inconsistent in its identification of different versions of browsers. For example, Internet Explorer 9 will appear as MSIE 9.0 while Internet Explorer 11 (which despite forsaking the family name still wields the trident of its ancestors) will appear as Internet Explorer 11. Since you have direct control over the name returned for a trident-detected version of IE, why not return "MSIE" instead of "Internet Explorer"?

Super minor nitpick: you misspelled "guarantee" in the code comments.

\$\endgroup\$
  • \$\begingroup\$ Thanks for the input, I have updated the fiddle(now v31) with your point of inconsistency and it is an improvement. \$\endgroup\$ – Neil Masters Mar 4 '15 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.