Browser detection using JavaScript – Tip JavaScript

Browser detection using JavaScript – Tip JavaScript cover image
  1. Home
  2. JavaScript
  3. Browser detection using JavaScript – Tip JavaScript

With a little help from JavaScript, you can easily detect the browser used by visitors on your web site. Browser detection has several uses. It helps you analyze your visitors if you store this information in a database, which assists you in building visitor profiles for better web site maintenance. You can redirect visitors to browser specific pages or display browser specific content such as style sheets.

The code described in this tip will concentrate on Netscape and Internet Explorer since they share more than 90% of the browser market. However, the code can be extended to detect other browsers.

<script type="text/javascript">
<!--

function whichname()
   {
   var bname = navigator.appName;
   alert("You are using " + bname);
   }

//-->
</script>

Click here to see how this works

The crux of this code is the appName property of the navigator object. This property contains the name of the browser. We assign this to a variable bname and then display it using the alert() method. (Simple enough?)
[Note: Our code resides in a function, which makes it possible to call it many times on a page. For example, I called this function using onLoad() in the body tag and again using onclick() in <a> for the link above.]

Redirection based on browser detected by JavaScript

Okay, now that you have learnt browser detection, we shall see how to implement it to redirect visitors to different pages depending on their browser.

<script type="text/javascript">
<!--

var bname = navigator.appName;
if (bname.search(/netscape/i) == 0)
   {
   window.location="nn.html";
   }
else if (bname.search(/microsoft/i) == 0)
   {
   window.location="ie.html";
   }
else
   {
   window.location="other_browsers.html";
   }

//-->
</script>

After assigning the browser name to bname, we search for the presence of specific words using JavaScript Regular Expressions. (JavaScript Regular expressions have been included in version 1.2 of the language and are based on those found in the Perl language. So if you were familiar with Perl, picking up the JavaScript regular expressions would be very simple).
The search() method searches for the string specified between the two forward slashes “/“. The ‘i‘ modifier makes it possible for case sensitive searches.
The JavaScript If tests whether condition is true or false. Thus, Netscape users are redirected to nn.html, Internet Explorer users to ie.html and other browsers to “other_browsers.html”.
The above code has to be placed inside the HTML head. It can also be contained inside a function which can be called using the onload().

JavaScript