Java Reference
In-Depth Information
If the browser is Firefox, IE9 or 10, Safari, Chrome, or Opera, a message appears telling users that
the browser is supported. If it's an earlier version of IE, the user sees a message telling him or her the
version of that browser is not supported.
If it's not one of those browsers (including IE11+), the user sees a message saying the browser is
unsupported.
At the top of the script block are two important functions. The getBrowserName() function finds out
the name of the browser and the getBrowserVersion() function finds out the browser version.
The key to the browser‐checking code is the value returned by the navigator.userAgent property.
Here are a few example user‐agent strings from current browsers:
1. Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR
3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko
2. Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.3; WOW64; Trident/7.0;
.NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729)
3. Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/34.0.1847.131 Safari/537.36
4. Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Here each line of the userAgent strings has been numbered. Looking closely at each line, it's not hard
to guess which browser each agent string relates to. In order:
1. Microsoft IE11
2. Microsoft IE10
3. Chrome 34.0.1847.131
4. Firefox 32
Using this information, let's start on the first function, getBrowserName() . First you get the name of
the browser, as found in navigator . userAgent , and store it in the variable lsBrowser :
function getBrowserName() {
var lsBrowser = navigator.userAgent;
The string returned by this property tends to be quite long and does vary. However, by checking for the
existence of certain keywords, such as MSIE or Firefox, you can usually determine the browser name.
Start with the following lines:
if (lsBrowser.indexOf("MSIE") >= 0) {
return "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 modified for Firefox:
else if (lsBrowser.indexOf("Firefox") >= 0) {
return "Firefox";
}
Search WWH ::




Custom Search