Monday, September 27, 2010

Detecting Google Chrome in ASP.NET code behind



We recently got a requirement to detect the browser type and browser version in our cross browser compatible application. Now, immediately we had two choices. Either we can do this from the Javascript or through code behind. We opted for the later due to the ease of implementation.

There are 2 ways (of which I am familiar) by which we can achieve this:


Using System.Web.HttpBrowserCapabilities Class which includes a Browser property through which
we can get Browser, MajorVersion and MinorVersion.
(MSDN Article)
 
(Or)
 
Using Request.UserAgent Property through which we can get the raw user agent string of the client browser.
(MSDN Article)
 
We went for the former approach and quickly found out that since Google Chrome and Apple Safari are both based on the WebKit layout engine, Browser.browser returns “AppleMAC-Safari” for both browsers!

When we try to get the user agent string, it however makes more sense, see below:


For Safari:


"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.1 Safari/525.17"

For Chrome:


"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.30 Safari/525.13"


So in order to distinguish between Safari and Chrome, we added one more step to the process i.e. We check the UserAgent String to see if it contains Chrome keyword.
if (Request.UserAgent.ToLower().Contains("chrome"))
{
strBrowserType = "Chrome";
}

That seemed to solve the issue of browser recognition!

3 comments: