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.

A Note About Caching

Most CMS, including Drupal on which this site is based [ed: not any more], 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. This produces a block of text something like the following - obviously varying with each browser type and redering engine:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

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.

<?php
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]> Something Here <![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 experience, 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 will work in most browsers, but not 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 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 browser-specific 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.


Click here to comment on this page.