Helping ordinary people create extraordinary websites!

Detecting Browsers

Often you will find that, due to slight variations in the functioning of different browsers, you need to write a particular some JavaScript code for one browser and different JavaScript code for another. So, how do you detect which browser the code is currently running on? The process of doing so is called browser sniffing, and is achieved by scanning the user agent string. The user agent string is an environment-specific string detailing the software being used by the user, and is made available to the server and to JavaScript scripts.

Detecting Internet Explorer

Detecting Internet Explorer is easy, as the user agent string - available in navigator.userAgent - will always include the text "MSIE". We can then check for this in a simple indexOf:

if (navigator.userAgent.indexOf('MSIE') !=-1)
{
// Using IE
}

"Mozilla" Firefox?

One would think that to detect Mozilla's Firefox and Seamonkey web browsers, it would be a simple matter of looking for "Mozilla" in the user agent. Not so - if we try this, it should function on almost every desktop browser. This is because, in the beginning when web browsers with JavaScript were in their infancy, it was typically the Mozilla browser engine and Netscape's browser that provided the best support for dynamic client-side scripting.

Many developers proceeded to look for "Mozilla" and only provide their functionality to users of this browser. To imitate this to some extent, Internet Explorer's user agent string is something like "Mozilla/4.0 (compatible; MSIE 6.0; ...)". Unfortunately, Internet Explorer is no longer as "compatible" as it once was, and browser sniffing is an unfortunate necessity of complex JavaScript development.

Detecting Firefox

Thankfully, Firefox places a "Firefox" in its user agent string that is reliable for detecting it:

if (navigator.userAgent.indexOf('Firefox') !=-1)
{
// Using IE
}

Detecting other browsers

Most popular browsers are built on either the Internet Explorer engine (e.g. Maxthon/MyIE) or the Mozilla Gecko engine (e.g. Firefox, Flock, K-Meleon). Supporting other Mozilla browsers can usually be achieved by looking for "Gecko" in the user agent string. Beyond this, you can experiment with other web browsers; download them and try them out - you can check the user agent string by entering javascript:navigator.appName in the address bar.

« JavaScript Strings


More JavaScript Tutorials:
» Answers To Questions About JavaScript
» Ensuring Two Form Fields Have Identical Information
» Pre-Fill Forms From Last Use
» A Simple Image/Link Rollover in Javascript
» Disabling the Right-click Mouse Button
» Dynamic External JavaScript Files