« Updates and fixes for Microformats CFC | Main | Validating multiple emails in one field »

Simple browser and OS sniffing in ColdFusion

It still happens these days that every so often you have to write different code for different browsers-- you might output different form controls for Firefox versus IE, or might write in different stylesheets for older browsers, or you might write out different JavaScripts for IE5 on the Mac. So what's the easiest way to tell which browser and OS is calling your page?

Obviously, you can look through the server's CGI variables too see this information. But you don't want to parse through it every time you have an if-else condition, so I suggest identifying this information once per request or even just once per session with the following code:

<!--- Get the user's platform and browser --->
<cfif CGI.HTTP_USER_AGENT contains "MSIE">
	<cfset REQUEST.userAgent = "IE">
<cfelseif CGI.HTTP_USER_AGENT contains "Opera">
	<cfset REQUEST.userAgent = "OP">
<cfelseif CGI.HTTP_USER_AGENT contains "Safari">
	<cfset REQUEST.userAgent = "SF">
<cfelseif CGI.HTTP_USER_AGENT contains "Netscape">
	<cfset REQUEST.userAgent = "NS">
<cfelseif CGI.HTTP_USER_AGENT contains "Gecko">
	<cfset REQUEST.userAgent = "MZ">
<cfelse>
	<cfset REQUEST.userAgent = "NS">
</cfif>

<cfif CGI.HTTP_USER_AGENT contains "Mac">
	<cfset REQUEST.platform = "Mac">
<cfelseif CGI.HTTP_USER_AGENT contains "Linux">
	<cfset REQUEST.platform = "Linux">
<cfelse>
	<cfset REQUEST.platform = "PC">
</cfif>

Afterwards, you can just refer to REQUEST.userAgent and REQUEST.platform to get the user's environment.

Comments (2)

The only way I could get it to accept the changes to the variable was to set each one individually like this:





Then insert a whatever here

Tried using your logic in the onRequest Scope from the Application.cfc Kept producing a blank page trying it with your logic above. What do you think?

cfset request.IsIE = CGI.HTTP_USER_AGENT contains 'MSIE'
cfset request.IsOP = CGI.HTTP_USER_AGENT contains "OP"
cfset request.IsSF = CGI.HTTP_USER_AGENT contains "SF"
cfset request.IsNS = CGI.HTTP_USER_AGENT contains "NS"
cfset request.IsMZ = CGI.HTTP_USER_AGENT contains "MZ"

cfif request.IsIE whatever here cfif

It stripped out the code had to repost code.