Java Reference
In-Depth Information
Using this information, let's start on the fi rst function, getBrowserName(). First you get the name of
the browser, as found in navigator.userAgent, and store it in the variable lsBrowser. This will also
be used as the variable to store the return value for the function.
function getBrowserName()
{
var lsBrowser = navigator.userAgent;
The string returned by this property tends to be quite long and does vary slightly sometimes. However,
by checking for the existence of certain keywords, such as MSIE or Firefox, you can determine the
browser name. Start with the following lines:
if (lsBrowser.indexOf(“MSIE”) >= 0)
{
lsBrowser = “MSIE”;
}
These lines search the lsBrowser string for MSIE. If the indexOf value of this substring is 0 or greater,
you know you have found it, and so you set the return value to MSIE.
The following else if statement does the same, except that it is modifi ed for Firefox.
else if (lsBrowser.indexOf(“Firefox”) >= 0)
{
lsBrowser = “Firefox”;
}
This principle carries on for another three if statements, in which you also check for Chrome, Safari,
and Opera. If you have a browser you want to check for, this is the place to add its if statement. Just
view the string it returns in navigator.userAgent and look for its name or something that uniquely
identifi es it.
If none of the if statements match, you return UNKNOWN as the browser name.
else
{
lsBrowser = “UNKNOWN”;
}
The value of lsBrowser is then returned to the calling code.
return lsBrowser;
}
Now turn to the fi nal function, getBrowserVersion() .
The browser version details often appear in the userAgent string right after the name of the browser.
For these reasons, your fi rst task in the function is to fi nd out which browser you are dealing with. You
declare and initialize the browser variable to the name of the browser, using the getBrowserName()
function you just wrote.
function getBrowserVersion()
{
var findIndex;
var browserVersion = 0;
var browser = getBrowserName();
Search WWH ::




Custom Search