Somebody
Somebody

Reputation: 9645

Compare browser versions via javascript

How to compare browser versions via javascript?

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

Is there any way?

Upvotes: 2

Views: 1421

Answers (5)

koko
koko

Reputation: 958

This code gets the version number of Firefox:

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...') }
}

Upvotes: 4

Mehmet Hazar Artuner
Mehmet Hazar Artuner

Reputation: 77

Parse version strings as float type, then compare them with if statement or whatever you want.
Here is a sample I've used for checking 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
}

Upvotes: 0

Petrica G
Petrica G

Reputation: 1

This fails now with Firefox getting 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;
}

Upvotes: 0

Juriy
Juriy

Reputation: 5111

Use navigator.userAgent in javascript

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

For firefox the last number is the version.

Upvotes: 1

karim79
karim79

Reputation: 342635

You should employ object/feature detection to ensure that something will work before you apply it. From that link:

While browser detection works well enough for 90% of your visitors, some obscure browsers won't be treated correctly and browsers that appear after you've written the page may not be adequately covered either. The results would be either a stream of error messages or a script that isn't called while the browser can easily handle it. In both cases, you're cheating your end users and coding incorrectly.

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

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

Upvotes: 7

Related Questions