JavaScript- Browser Detection.

Posted on 26/09/2009 by

1



Browser Detection

Almost everything in this tutorial works on all JavaScript enabled browsers. There are also some things that just don’t work on certain browsers, especially on older browsers. Sometimes it can be very useful to detect the visitor’s browser and then serve your way up to the appropriate information.
The best way is to make your web pages look smart enough, one way to some browsers and another way to other browsers.
JavaScript also includes an object which is called the Navigator that can be used for this purpose..It contains information about the visitor’s browsers name, version and much! much! more.

The JavaScript Navigator object contains all kinds of information about the visitor’s browser. We are going to look at two properties of the Navigator object:

  • appName – holds the name of the browser
  • appVersion – holds, among other things, the version of the browser

Browser Detection

Example:

The Input

<html>
<body>
<script type=”text/javascript”>
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
document.write(“Browser name: “+ browser);
document.write(“<br />”);
document.write(“Browser version: “+ version);
</script>
</body>
</html>

The Output

Browser name: Netscape
Browser Version 5

The variable browser in the example holds the name of the browser, “Netscape” or Microsoft Internet Explorer”

The appVersion browser in the example above returns a string that only contains much more information than just the version number and for nowwe are only interested in the version number. To pull the version number out of the string we are going to use a function called parseFloat() which pulls the first thing that looks like a decimal number out of a string and returns it.

Example:

<html>
<head>
<script type=”text/javascript”>
function detectBrowser()
{
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
if ((browser==”Netscape”||browser==”Microsoft Internet Explorer”) && (version>=4))
{
alert(“Your browser is good enough!”);
}
else
{
alert(“It’s time to upgrade your browser!”);
}
}
</script>
</head>

<body onload=”detectBrowser()”>
</body>

</html>

EllaHax

Advertisements
Posted in: Coding, JavaScript