Display browser information

As you create web pages, you may realize they look different in different browsers. By learning browser type, version number, installed plug-ins, etc., can help you better design your web pages. For example, you could control/style the display of the content based on a specific browser type. This page explains how to direct the browser to a specific page based on the browser version.

The script below shows a function called ShowBrowserDetails () that outputs browser name, browser version number, if Java is enabled, screen width, and screen height.

The following shows the output of the script:

Browser details

Name: Netscape
Version: 5.0
Java enabled: false
Screen width: 1536
Screen height: 864

Scripting code

Step 1: place the following code in the head section (between <head> and </head>) of your web document:

<script language="javascript">
function ShowBrowserDetails() {
var BrowserName = navigator.appName; //gets the name of the browser
var appVersion = navigator.appVersion.substring(0,4); // browser version
var isJavaEnabled = navigator.javaEnabled(); // checks if Java is enabled
var screenWidth = screen.width; // get screen width
var screenHeight = screen.height; // get screen height
// the following stores the output in outputStr variable
var outputStr = "<h1>Browser details</h1>";
outputStr = outputStr + "<p>Name: " + BrowserName;
outputStr = outputStr + "<br>Version: " + appVersion;
outputStr = outputStr + "<br>Java enabled: " + isJavaEnabled;
outputStr = outputStr + "<br>Screen width: " + screenWidth;
outputStr = outputStr + "<br>Screen height: " + screenHeight + "</p>";
document.write (outputStr); // print
}
</script>

In the function definition shown above, we basically declare 6 variables:

  1. BrowserName — this stores the name of the browser
  2. appVersion — this stores the browser version number
  3. isJavaEnabled — this variable holds whether or Java is enabled on the browser.
  4. screenWidth — this holds the width of the screen
  5. screenHeight — holds screen height
  6. outputStr — holds the output

Notice how we add output to the outputStr variable by using the concatenate operator (+). This eliminates the need of using bunch of document.write () statements.

Step 2: Call the above function (ShowBrowserDetails()) from your web page:

<script language="javascript">
ShowBrowserDetails(); // calling the function
</script>

In step 2, we instruct the browser to execute our function called ShowBrowserDetails (). As the function executes, it stores the output to the designated variables before all is printed with the document.write () statement, as shown above.