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;
}
asked Mar 3, 2015 at 22:04
\$\endgroup\$

1 Answer 1

1
\$\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.

answered Mar 3, 2015 at 23:45
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the input, I have updated the fiddle(now v31) with your point of inconsistency and it is an improvement. \$\endgroup\$ Commented Mar 4, 2015 at 9:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.