Compare browser versions using javascript

How do I compare browser versions using javascript?

For example, if the script wants to know if the user is using Firefox 3.5+

Is there a way?

+2


a source to share


5 answers


This code gets the Firefox version number.

var FFVersion = navigator.userAgent.substring (navigator.userAgent.indexOf ("Firefox")). split ("/") [1];



You decide what to do with each of them:

  window.onload = function() {
        if (FFVersion < '3.5') { alert('please upgrade...') }
    }

      

+2


a source


You should use object / function detection to make sure something will work before applying it. From this link:

While browser detection works well enough for 90% of your visitors, some obscure browsers will not be viewed correctly and browsers that appear after you have written the page may not be adequately covered either. the results will be either a stream of error messages or a script that is not called when the browser can handle it easily. In both cases, you are cheating your end users and coding wrong.



To get the browser version, you can use the Navigator object :

alert(navigator.appName + ' ' + navigator.appVersion);

      

+6


a source


Use navigator.userAgent in javascript

You will get a line like "Mozilla / 5.0 (Windows; U; Windows NT 6.1; en-GB; rv: 1.9.2). Gecko / 20100115 Firefox / 3.6"

For firefox, the latest version is.

+1


a source


Now this fails from Firefox to 10.0. Come up with a different version:

// Takes 2 strings "2.3.4.5" and "2.5" and returns less, equal and greater than 0
// depending which one is bigger
function compareVersions(a, b) {
  var v1 = a.split('.');
  var v2 = b.split('.');
  for(var i = 0; i < Math.min(v1.length, v2.length); i++) {
    var res = v1[i] - v2[i];
    if (res != 0)
      return res;
  }
  return 0;
}

      

0


a source


Parse version strings as floats, then compare them with an if statement or whatever you want.
Here's an example I used to check the IE browser version:

if(parseFloat($.browser.version) <= 8.0)
{
    // Do whatever you want if browser version lower than equal to 8.0
}
else
{
    // Do whatever you want if browser greater than 8.0
}

      

0


a source