Tuesday 8 November 2011

Detecting User Agent in Server side or Client side code

If you are writing code that requires information about the type of browser, application or operating system that is accessing your website, you need to detect User Agent information from the client device. You may be doing this to load different stylesheets based on the type of browser, load extra functionality for more modern browsers, display a 'please upgrade' message in older browsers, or for a multitude of other reasons.

Obtaining User Agent information can be achieved in a number of ways. The methods shown here include using server-side code such as Java, PHP or C#, and using client-side JavaScript code.

1. Get User Agent information from Request Headers

In server-side code such as C#, PHP or Java, you can access the User-Agent (or client browser) using the following syntax or similar:
PHP: $_SERVER['HTTP_USER_AGENT']
C#: Request.UserAgent;
Java: request.getHeaderNames(), find User-Agent

You can also access other useful information from the Request Headers such as the Accept value, which informs the server which data types the client browser is willing the accept.

Once you have the User Agent information, you can set the list of CSS files to load in the server side code.

2. Detect User Agent using JavaScript

For some media types such as desktop and laptop screens or hand-held mobile device display panels, you might be able to use JavaScript code to detect the User Agent or media type.

The navigator object is used often in JavaScript to detect browser or operating system type information using the following navigator properties:
  • appCodeName, e.g. Mozilla
  • appName, e.g. Netscape
  • appVersion, e.g. 5.0 (Windows)
  • platform, e.g. Win32
  • userAgent, e.g. Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1

A disadvantage of this method is that you are relying on your browser to support JavaScript, which is probably not the case for all media types. Browser detection scripts are also often unreliable and prone to bugs.

References:

MSDN - HttpRequest.UserAgent Property
About.com - $_SERVER['HTTP_USER_AGENT']
Reading HTTP Request Headers
Wikipedia - MIME
W3Schools - JavaScript Browser Detection
Wikipedia - User Agent


No comments:

Post a Comment