Determining browser type and version Script
Here’s another, more advanced, example that determines which browser the user has and lets you execute code depending on browser type to display the browser version.
This example puts to use the if and else statements as well as several built-in JavaScript functions that handle strings. In JavaScript, text strings are considered objects, and they have some built-in properties and methods that make life easier.
Here’s what this example uses:
The length property gives you the length of the string, in characters The indexOf method searches for the occurrence of a substring and gives you the location of the first match — or –1 if there was no match. (The first character of a string is considered character 0.) The substring method lets you extract a substring from a larger string. You can pass this method the start and end locations of the substring that you want to extract.
This example searches the navigator.userAgent property, which, as I introduce in "Which browser are you using?", holds the browser name and version, extracts that information, and displays it. (You really don’t have to memorize the string functions here — I put together this example because it’s often important in Ajax programming to know what browser and version the user has.).
The script looks like.
<html>
<head>
<title>
Determining your browser
</title>
<script language=”javascript”>
var versionBegin, versionEnd
function checkBrowser()
{
if(navigator.appName == “Netscape”) {
if(navigator.userAgent.indexOf(“Firefox”) > 0) {
versionBegin = navigator.userAgent.indexOf(“Firefox”) +
“Firefox”.length + 1;
versionEnd = navigator.userAgent.length;
document.getElementById(“targetDiv”).innerHTML =
“You have Firefox “ +
navigator.userAgent.substring(versionBegin, versionEnd);
}
}
if (navigator.appName == “Microsoft Internet Explorer”) {
versionBegin = navigator.userAgent.indexOf(“MSIE “) +
“MSIE “.length;
if(navigator.userAgent.indexOf(“;”, versionBegin) > 0) {
versionEnd = navigator.userAgent.indexOf(“;”, versionBegin);
} else {
versionEnd = navigator.userAgent.indexOf(“)”, versionBegin)
+ 2;
}
document.getElementById(“targetDiv”).innerHTML =
“You have Internet Explorer “ +
navigator.userAgent.substring(versionBegin, versionEnd);
}
}
</script>
</head>
<body onload=”checkBrowser()”>
<h1>Determining your browser</h1>
<div ID=”targetDiv”></div>
</body>
</html>
You can see the results in picture below, where the user is using Firefox 1.0.6. Using code like this, you can figure out what browser the user has — and whether the browser he has doesn’t do what you want, put in some kind of workaround.
One thing computers are good at is doing the same kind of task over and over, and JavaScript helps out here with loops. I take a look at them in the following
section to set the stage for working with buttons in Web pages that the user can click.