Detecting Browser Type

Saturday, June 14, 2008

Since some css/don't run the same way on every browser, sometimes you have to detect what browser type is your visitor using, then decide what to do to your visitor accordingly.

The navigator JavaScript object provides browser informations, the most useful, but also sometimes not-easy to parse, is its userAgent property, which contains the complete browser identification string that is also sent in the HTTP User-Agent header with each request.

If you just want to determine the browser type, the window.alert(navigator.appName) will suffice, however the value returned is not always correct so you still have to look to the navigator.userAgent like this:<> br /

<script language="JavaScript" type="text/javascript">
var uA = navigator.userAgent;
var browserType = "unknown";
if (uA.indexOf("Opera") > -1) {
 browserType = "Opera";
} else if (uA.indexOf("Safari") > -1) {
 browserType = "Safari";
} else if (uA.indexOf("Konqueror") > -1) {
 browserType = "Konqueror";
} else if (uA.indexOf("Gecko") > -1) {
 browserType = "Mozilla";
} else if (uA.indexOf("MSIE") > -1) {
 browserType = "Internet Explorer";
}
window.alert(browserType);
</script>

As you can see, opera is checked first since the browser can identify itself as another browser. The point here is, with some effort to userAgent you can extend the script to detect more than just the name of the browser type, you can even get the version or the derivatives(with example as mozilla: k-meleon, firefox, ephipany, camino, etc).

More references can be found in http://www.webreference.com/tools/browser/javascript.html and http://gemal.dk/browserspy/basic.html

Hope this helps.

0 comments: