Detect browser name and version using js

I was trying to detect browser version and browser name using java script. I got so many techniques but I am happy with jquery’s one. It’s pretty simple and small block of code. Just check the bellow code that I got from jquery. As it is not possible to use the whole js library all the time but I like to use some part of it or follow the techniques for cross browser tasks. 😀

//Detect browser version
var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
var browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
alert('Browser Version='+browser.version.toString()+ ' Safari='+(browser.safari? 'Yes': 'No')+' Opera='+(browser.opera? 'Yes': 'No')+' IE='+(browser.msie? 'Yes': 'No')+' FF='+(browser.mozilla? 'Yes': 'No'));
//end browser detection

Edit: Here one thing you may be confused about the test() method. It’s a builtin function in js. The test() method is used to search for a match of a regular expression in a string.

Here’s some links about Test();

  1. Email Address valiadtion
  2. W3 school link

4 Responses to “Detect browser name and version using js”

  1. i think this is also a simple method to detect browser
    $(document).ready(function()
    {
    if ( $.browser.msie ){
    if($.browser.version == ’6.0′)
    {
    $(‘html’).addClass(‘ie6′);
    }
    if($.browser.version == ’7.0′)
    {
    $(‘html’).addClass(‘ie7′);
    }
    if($.browser.version == ’8.0′)
    {
    $(‘html’).addClass(‘ie8′);
    }
    if($.browser.version == ’9.0′)
    {
    $(‘html’).addClass(‘ie9′);
    }
    }
    else if ( $.browser.webkit )
    { $(‘html’).addClass(‘webkit’);
    }
    else if ( $.browser.mozilla )
    { $(‘html’).addClass(‘mozilla’);
    }
    else if ( $.browser.opera )
    { $(‘html’).addClass(‘opera’);
    }
    });
    

Leave a Reply

Your email address will not be published. Required fields are marked *