JavaScript Tip of the Week for June 24, 1996: Too Many Browers? Wrong. | WebReference

JavaScript Tip of the Week for June 24, 1996: Too Many Browers? Wrong.

JavaScript Tip of the Weekfor June 24, 1996: Part 1. Determing Which Browser is Being Used


But the JavaScript code for this week detects, using built in Netscape features, whether you have Netscape 3.0, 2.0, or MSIE. How is this done? The JavaScript checks through the browser's info and finds out if it is Netscape 3.0 or 2.x. If it doesn't find either of these, it defaults to MIE. If any new versions of the software come out, the code can easily be updated.

It is important that you know Netscape has some special JavaScript functions. The functions that this code uses looks like navigator.userAgent.indexOf. What this code does is find out which version of Netscape it is, which platform it's on, etc. Here is the code that does this:
var version = 0;
    if (navigator.userAgent.indexOf("Mozilla/3.0") != -1) version = 3;
    else if (navigator.userAgent.indexOf("MSIE") != -1) version = 1;
    else if (navigator.userAgent.indexOf("Mozilla/2.0") != -1) version = 2;
    else version = 0;

The first thing that this code does is creat a variable named version. This variable will be used throughout the page to quickly determine which browser is being used. Just so you know, the code name for Netscape's browser is "Mozilla", and that is what these functions refer to Netscape as. The Script checks for Netscape 3.0, if it finds that the browser is 3.0, then it sets version to 3. Then it checks for Netscape 2.x and then for Microsoft Internet Explorer, and if it finds either of these it sets version to 2 or 1, respectively. If it finds neither of these, then it sets version to 0.

When you click on the button, it tells you which version it has detected. The code for this is very simple. The code for the button (not the button image changing) looks like this:
    <A HREF = "JavaScript:alert('You are using ' + which_one())">
    <IMG HEIGHT = 42 WIDTH = 105 BORDER = 0 SRC = "test_inactive.jpg"></A>

When the button is pressed, function which_one() is run:
function which_one()
    {
    if (version == 3) return "Netscape Version 3.0";
    if (version == 2) return "Netscape Version 2.x.";
    if (version == 1) return "Microsoft Internet Explorer 3.0";
    if (version == 0) return "A browser I've never heard of"
    }

Function which_one simply returns one of four messages, each depending on what the variable version is set to. In the rest of the document it is now very easy to show which browser the viewer is using (this may seem a little obvious). Just use code similar to this:
     if (version == version number here) preform code
Source