The University of Texas at Austin- What Starts Here Changes the World
Services Navigation


Example 2 - Detecting the Browser

Example 1 illustrated how to create Javascript and how it functions in a page. Let's look at a more useful example, detecting what browser someone is using. Browser detection is often useful because all browsers do not support Web technologies equally, For example, you might want to detect if someone is using the latest version of a browser before you use Cascading Style Sheets.

<HTML>
<HEAD>
<TITLE> Hello World in Javascript </TITLE>
</HEAD>
<BODY>
<h2>Example 1</h2>


<script language="Javascript">
// Detecting the browser


// detect what browser they are using and store it in a variable
// called browser

var browser = navigator.appName;
var version = navigator.appVersion;

alert(browser + " " + version);

if (browser.indexOf("Internet Explorer" > -1) {
   document.write("Go to www.microsoft.com to download the latest browser version");
} else {
   document.write("Go to www.netscape.com to download the latest browser version");
}


</script>


</BODY>
</HTML>

This example illstrates two new concepts, detecting what browser someone is using and a conditional to perform different code based on the result. This script uses the navigator object to get information about the browser being used. The appName property returns the name of the browser and the appVersion returns the version of the browser. In the example, these two values are stored in variables called browser and version.

The alert method is often helpful in debugging. The method displays a pop-up alert box with the message or value in parentheses. In this case, it displays the value of the browser and version variables separated by a space.

The if statement tests the browser variable to see if it contains particular values. The general syntax of a conditional is:

if (condition) {
   statement(s) to execute if condition is true;
} else {
   statement to execute if condition is false;
}

In our example. we test whether the browser variable contains particular characters by using the indexOf property. This property returns the location of one string within another. A value of -1 is returned if the string is not present.

Test Example 2

 


  Updated 2003 September 29
  Comments to www@www.utexas.edu