Click to See Complete Forum and Search --> : Determining browser version?


Xeon
May 21st, 2009, 06:06 AM
Been trying to find this everywhere, on how to determine the user's browser version (IE 7.0, IE 8.0, IE 6.0, FireFox 2.0 etc.) using JavaScript.

The few sources which I googled were badly outdated (most written in 2003) and I'm not sure if they could be used.

Anyone has the code, and has a good URL?

Thanks! :)
Xeon

PeejAvery
May 21st, 2009, 08:10 AM
I typically prefer to do browser detection on the server-side using the browser agent, so this is a simple port from PHP to JavaScript. If you care about the small name browsers, you can add them yourself using one of the two if templates below.

<script type="text/javascript">
function getBrowserInfo() {
var userAgent = navigator.userAgent;
var tmpBrowser = "Unknown";
var tmpVersion = "";

if(userAgent.search(/MSIE/i) > 0){
tmpBrowser = "Internet Explorer";
var parts = serAgent.toLowerCase().match(/msie\s(.*?);/i);
tmpVersion = parts[1];
}
if(userAgent.search(/Mozilla/i) > 0){
tmpBrowser = "Mozilla";
var parts = serAgent.toLowerCase().match(/mozilla\/(.*?)\s/i);
tmpVersion = parts[1];
}
if(userAgent.search(/Firefox/i) > 0){
tmpBrowser = "Firefox";
var parts = userAgent.toLowerCase().split("firefox/");
tmpVersion = parts[1];
}
if (userAgent.search(/Safari/i) > 0) {
tmpBrowser = "Safari";
var parts = userAgent.toLowerCase().split("safari/");
tmpVersion = parts[1];
}

var tmpReturn = {};
tmpReturn.browser = tmpBrowser;
tmpReturn.version = tmpVersion;
return tmpReturn;
}

var browserInfo = getBrowserInfo();
document.write(browserInfo.browser + " " + browserInfo.version);
</script>

Xeel
May 21st, 2009, 07:12 PM
If the question is more about browser's version and not the type:
depending on browser the version number could be contained inside userAgent attribute or in the appVersion. I'd recommend playing with these three and parse them as you need:<script type="text/javascript">
alert("appName: "+navigator.appName+"\n\n"+
"userAgent: "+navigator.userAgent+"\n\n"+
"appVersion: "+navigator.appVersion);
</script>

For more info: http://www.javascriptkit.com/javatutors/navigator.shtml

PeejAvery
May 21st, 2009, 10:31 PM
That solution will only work on older browsers. For example, it's claiming that both my Safari 4.0 and Firefox 3.0.6 are Netscape 5.0.

Xeel
May 22nd, 2009, 12:24 PM
That solution will only work on older browsers.
This solution does work right now. Yes, the engine is GRE, so it says Netscape for the appName, however the userAgent and appVersion work as they should. As I said before: using all three attributes one can detect any browser and its version, just need to play a bit with parsing. This is a valid statute.

In any case it's not so important to know the exact browser version but the engine it uses. So a good browser detect would be some js or IE expression validation. This way a developer knows for sure if it's Gecko, IE, Opera or anything else.