Personal Blog Post:

Browser Detection Methods

Whilst there may be many reasons for wanting to know which browser your web page is being viewed within, the main one I find is needing to tweak some CSS or embedded applet code to accommodate certain rendering inconsistencies. At first glance, this seems pretty easy with dynamically-generated pages as most server-side programming or scripting languages provide a way of doing this as the page is being assembled for delivery. However, for both static web pages and content that is likely to be cached by a content management system (CMS) it isn't so easy. This article therefore considers a range of available browser detection methods.

Server-Side Detection

Detecting the browser on the server-side is the easiest option, assuming you have access to the page assembly code. It basically means that you can test for the browser type at any time whilst generating a page in order to specifically tailor the content or its associated style sheets to suit the requesting browser.

IMPORTANT WARNING: Most CMS, including Drupal on which this site is base, implement some sort of server-side content caching mechanism to avoid having to regenerate everything all the time. As clearly demonstrated in my attempts to embed Java applets, the server-side cache will likely contain the version served up to the very first browser that requested the page immediately after the last modification or cache clearance. You need to be very careful with server-side browser detection with such systems and test your page on lots of different browsers and under lots of different conditions.

In PHP the global variable $_SERVER['HTTP_USER_AGENT'] stores information sent by a browser when requesting a web page. For example, your browser sent the following User Agent information to this web server:

CCBot/2.0 (http://commoncrawl.org/faq/)

Using this block of text, you can do browser detection simply or you can go all out and detect type, platform and version number. The website apptools.com provide a comprehensive browser class script for this level of detail. However, for most of my tasks I just need the browser type so a fairly simple detection function such as that given below is all that is needed.

function _my_get_browser_type() 
{
  if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) $browser = 'safari';
  else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko')) 
  {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape')) $browser = 'netscape';
    else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) $browser = 'firefox';
    else $browser = 'mozilla';
  }
  else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) $browser = 'ie';
  else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === true) $browser = 'opera';
  else $browser = 'other';
  return $browser;
}

This function returns an easy to test string specifying the type of browser being used so you can include extra style sheet references, Javascript functions or HTML code as and when required. This function can be used in any PHP cope block or embedded within a PHP-generated web page as follows:

<!-- Common HTML/CSS/JAVASCRIPT here... -->
<?php if (_my_get_browser_type() == 'ie'); ?>
<!-- Add some Internet Explorer specific HTML/CSS/JAVASCRIPT here... -->
<?php endif; ?>
<!-- More common HTML/CSS/JAVASCRIPT here... -->

This can be done within both the header and body of a page.

Client-Side Detection

Client-side detection is a bit more interesting as you have to rely on the local browser with all its potential foibles. However, this can be done using either specially formatted comments within the HTML code or by embedded Javascript to create or modify parts of the page dynamically.

Using Conditional Comments

Microsoft introduced conditional comments in Internet Explorer 5 (IE) to allow developers to take advantage of its enhanced features while still allowing their pages to downgrade gracefully in less-capable browsers. According to Microsoft, "Conditional comments are the preferred means of differentiating Cascading Style Sheet (CSS) rules intended for specific versions of Internet Explorer". Since then, many other browsers have introduced their own support for these constructs.

Using conditional comments means embedding <!--[if IE]> HTML <![endif]--> tags within the HTML code of each page. As everything is contained within standard XHTML <!-- --> code comment tags, browsers that do not support such conditionals will simply treat the whole thing as a hidden comment. IE, on the other hand, will recognise and process the appropriate parts as if they were not wrapped in a comment.

Thus, it is possible to include a special stylesheet just for Internet Explorer by adding the following within the <head> section of the web page.

<!--[if IE]>
<link href="css/ie_specific_styles.css" rel="stylesheet" type="text/css" />;
<![endif]-->;

Unfortunately, what you can't do is the opposite - including something specific to another browser that is not IE. Whilst most modern browsers now recognise these conditionals, in my experence, you can bet that the person you really want to be able to see the correct code can't.

Another issue is that there is some variation in exactly which expressions different browsers will respond to. For example, the following won't work in Firefox.

<!--[if !IE]>
<link href="css/other_styles.css" rel="stylesheet" type="text/css" />
<![endif]-->

However, remove the comment syntax like the following and it will work in Firefox. This is a format Microsoft calls the "Downlevel-revealed conditional comment".

<![if !IE]>
<link href="css/other_styles.css" rel="stylesheet" type="text/css" />
<![endif]>

Whilst this will probably end up working the way you want it to most of the time, such a construct is not standards compliant so may trip up some browsers and who knows when support may be withdrawn in a subsequent browser release.

In summary, conditional comments are great if you want to differentiate between Internet Explorer and all other browsers. However, a level of uncertainty and doubt prevails if you need to rely on it to differentiate between different browsers other than Internet Explorer.

Using Javacript

The main feature of using Javascript is that scripts are not typically executed until the entire web page is loaded into the browser and the base Document Object Model (DOM) is complete. Thus, the only way to introduce new code into a page is to use the document.write() function to insert new DOM elements as required. The other option is to use Javascript to modify or show/hide different parts of DOM once it has loaded.

The key to browser detection in Javascript is the system navigator object. This is a complex object with many member properties - the main two in this task being navigator.appName and navigator.appVersion. The following is an example script showing how to write out the various values in this object.

<script type="text/javascript">
document.write("Name=" + navigator.appName + "<br />");
document.write("Version=" + navigator.appVersion + "<br />");
document.write("CodeName=" + navigator.appCodeName + "<br />");
document.write("MinorVersion=" + navigator.appMinorVersion + "<br />");
document.write("CookieEnabled=" + navigator.cookieEnabled + "<br />");
document.write("CPUClass=" + navigator.cpuClass + "<br />");
document.write("OnLine=" + navigator.onLine + "<br />");
document.write("Platform=" + navigator.platform + "<br />");
document.write("UserAgent=" + navigator.userAgent + "<br />");
document.write("BrowserLanguage=" + navigator.browserLanguage + "<br />");
document.write("SystemLanguage=" + navigator.systemLanguage + "<br />");
document.write("UserLanguage=" + navigator.userLanguage);
</script>

For example, using this exact script embedded inside this page, the details extracted from your browser are as follows:


Thus, an example Javascript function that detects a specific browser might look like the following:

<script type="text/javascript">
if (navigator.appName == "Netscape")
{
  document.write("<p>You are using Netscape...</p>");
}
</script>

Using AJAX Tools Like jQuery

Javascript-based AJAX frameworks like jQuery are starting to revolutionise tasks like browser detection, fundamentally changing how they are done. For example, you could write a jQuery script to add an extra CSS class to the body of your document that is based on the browser type (body.browserIE, body.browserChrome, body.browserSafari, body.browserFirefox, etc). Then, all you need to do is add browser-class-specific CSS such as the following:

/* Standard formatting. */
div.frame img {
  width: 100%;
}
/* Special IE-specific formatting. */
.browserIE div.frame img {
  _width: 99%;
}

A good example of such a script is available at tvidesign.co.uk.

Your rating: None Average: 3 (20 votes)