1. Technology
Send to a Friend via Email

Browser Detection

clr gif
Join the Discussion

Questions? Comments?

One rather interesting statistic that you may wish to find out about visitors to your site is which web browser that they are using. Of course, there are a lot of different browsers and many try to pass themselves off as Internet Explorer in order to get scripts on the page that use primitive browser detection scripts instead of feature detection to function properly.

What this means is that many browsers do not identify themselves correctly in the navigator.appname field and so that field is not really useful for detecting which browser is really being used. The following script uses the navigator.userAgent fieldinstead and attempts to determine the correct browser from that. This field can also be set to values that attempt to trick primitive browser detection scripts into thinking that the browser is Internet Explorer instead of whatever browser it really is but the true browser name usually appears somewhere in the field as well and this more advanced browser detection script will only misidentify those browsers that have set out to completely conceal their true identity.

The first step in using this script is to select the code from the text box below (there is a highlight all button beneath it to make this easier) and copy it into a file called brsdet.js.

You next attach the script into your web page that needs to be able to determine which browser is being used by adding the following code into the head section of your page.

<script type="text/javascript" src="brsdet.js">
</script>

Now all that remains is to assign whichBrs() to whichever field that you want to contain the browser name. The statement can be used anywhere within the Javascript in your page. For example you might code it like this:

var browserName = whichBrs();

You can use the result from this browser detection script for statistical purposes or where you want to provide different information depending on which browser is being used.

You should not use browser detection to attempt to determine whether a visitor's browser supports particular functionality since there are dozens of different browsers (this script detects at least 15 different ones correctly) and the features provided by the different browsers changes between versions. Instead you should use feature detection if your script requires the use of a particular feature.

©2014 About.com. All rights reserved.