yan-k
9/17/2014 - 1:08 PM

JavaScript to return the current user agent and version as a string.

JavaScript to return the current user agent and version as a string.

function detectBrowserAndVersion()
{    
    var user_agent = navigator.userAgent, user_agent_version, user_agent_match = user_agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    
    if(/trident/i.test(user_agent_match[1]))
    {
        user_agent_version = /\brv[ :]+(\d+)/g.exec(user_agent) || [];
        return 'IE '+(user_agent_version[1] || '');
    }

    if(user_agent_match[1] === 'Chrome')
    {
        user_agent_version = user_agent.match(/\bOPR\/(\d+)/)
        
        if(user_agent_version !== null)
          return 'Opera '+user_agent_version[1];
    }
    user_agent_match = user_agent_match[2] ? [user_agent_match[1], user_agent_match[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if( ( user_agent_version = user_agent.match( /version\/(\d+)/i ) ) !== null )
      user_agent_match.splice(1, 1, user_agent_version[1]);
    return user_agent_match.join(' ').toLowerCase();   
}