How to Get Browser Name and Version via JavaScript
Today I ran into a strange issue where Firefox version 28 and below rendered style widths different than Firefox 29 and above. Firefox 29 and above appear to have fixed the issue and render sizes to match Chrome/IE8+/Opera/Safari. Unfortunately, as old as Firefox 28 is, our client’s legal review team is stuck on that version as IT refuses to let them upgrade. As such, we needed to add a kludge fix to the site to add a style to fix the issue for those running older Firefox versions. JQuery removed the version support from version 1.9 so here’s a handy script that will allow you to detect the browser and version without any extra dependencies.
function get_browser_info(){ var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if(/trident/i.test(M[1])){ tem=/\brv[ :]+(\d+)/g.exec(ua) || []; return {name:'IE ',version:(tem[1]||'')}; } if(M[1]==='Chrome'){ tem=ua.match(/\bOPR\/(\d+)/) if(tem!=null) {return {name:'Opera', version:tem[1]};} } M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?']; if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);} return { name: M[0], version: M[1] }; }
Usage is very simple:
var browser=get_browser_info(); console.log(browser.name); console.log(browser.version);
BONUS: If you need to detect a specific version and add special classes, here’s a quick snippet that will allow you to add a class to the HTML tagĀ using plain old vanilla.js.
var browser=get_browser_info(); if(browser.name == 'Firefox' && browser.version <= 28) { var root = document.documentElement; root.className += " firefox28"; }