Java Reference
In-Depth Information
If the browser is MSIE (Internet Explorer), you need to use the userAgent property again. Under IE, the
userAgent property always contains MSIE followed by the browser version. So what you need to do is
search for MSIE, then get the number following that.
You set findIndex to the character position of the browser name plus the length of the name, plus one.
Doing this ensures you to get the character after the name and after the following space or / character
that follows the name and is just before the version number. browserVersion is set to the fl oating-point
value of that number, which you obtain using the substring() method. This selects the character
starting at findIndex , your number, and whose end is one before findIndex , plus three. This ensures
that you just select three characters for the version number.
browserVersion = navigator.userAgent;
findIndex = browserVersion.indexOf(browser) + browser.length + 1;
browserVersion = parseFloat(browserVersion.substring(findIndex,findIndex + 3));
If you look back to the userAgent strings, you see that IE8's is similar to this:
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; .NET CLR 2.0.40607)
So findIndex will be set to the character index of the number 8 following the browser name.
browserVersion will be set to three characters from and including the 8 , giving the version number
as 8.0 .
At the end of the function, you return browserVersion to the calling code, as shown here:
return browserVersion;
}
You've seen the supporting functions, but how do you make use of them? Well, in the following code, which
executes as the page is loaded, you obtain two bits of information — browser name and version — and use
these to fi lter which browser the user is running.
var browserName = getBrowserName();
var browserVersion = getBrowserVersion();
if (browserName == “MSIE”)
{
if (browserVersion < 7)
{
document.write(“Your version of Internet Explorer is too old”);
}
else
{
document.write(“Your version of Internet Explorer is fully supported”);
}
}
The fi rst of the if statements is shown in the preceding code and checks to see if the user has IE. If true,
it then checks to see if the version is lower than 7. If it is, the user sees the message stating their browser
is too old. If it is 7+, the message tells the user their browser is fully supported.
You do this again for Firefox, Chrome, Safari, and Opera. The versions of these browsers aren't checked
in this example, but you can do so if you want to:
else if (browserName == “Firefox”)
{
Search WWH ::




Custom Search