Java Reference
In-Depth Information
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 identifies it.
If none of the if statements match, you return UNKNOWN as the browser name:
else {
return "UNKNOWN";
}
Now turn to the final function, getBrowserVersion() .
The browser version details often appear in the userAgent string right after the name of the browser.
For these reasons, your first task in the function is to find 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 ua = navigator.userAgent;
var browser = getBrowserName();
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 , and 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 just before the version number.
browserVersion is set to the floating‐point value of that number, which you obtain using the
substring() method. This selects the characters starting at findIndex and ending with the one before
findIndex , plus three. This ensures that you just select three characters for the version number:
var findIndex = ua.indexOf(browser) + browser.length + 1;
var browserVersion = parseFloat(ua.substring(findIndex, findIndex + 3));
If you look back to the userAgent strings, you see that IE10's is similar to this:
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.3; WOW64; Trident/7.0)
So findIndex will be set to the character index of the number 10 following the browser name.
browserVersion will be set to three characters from and including the 10 , giving the version number as 10.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 you
obtain two bits of information—browser name and version—and use these to filter which browser the
user is running:
var browserName = getBrowserName();
var browserVersion = getBrowserVersion();
if (browserName == "MSIE") {
Search WWH ::




Custom Search