Get browser name and version using Javascript

Question:

I want to write some functions that are multibrowser and for this I need to know through a function the name and the current version of the browser in the client, what would be the best way to do it in pure Javascript?

Answer:

The most accurate is to parse the UserAgent header; which contains data such as the browser, version and operating system.

In this answer the user makes use of regular expressions to obtain the browser and the version:

var getBrowserInfo = function() {
    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 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    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 M.join(' ');
};

console.log(getBrowserInfo());

Another option is to use the bowser package:

console.log(bowser.name, bowser.version);
<script src="https://cdnjs.cloudflare.com/ajax/libs/bowser/1.9.4/bowser.min.js"></script>
Scroll to Top