Wednesday 23 June 2010

Get browser information from Silverlight

Recently I needed to detect information about browser version within Silverlight. After googling around I found many posts that pointed to built-in class BrowserInformation, which can be accessed via System.Windows.Browser.HtmlPage.BrowserInformation.

So I should be happy and use its Name and BrowserVersion properties?

No, because BrowserVersion property returns something similar to HTML version instead of the real browser version. For example, on "Internet Explorer 7.0", it returns "4.0"

The "real" browser version can be extracted from the mysterious UserAgent property, just like this:

public static string BrowserName()
{
  string userAgent = HtmlPage.BrowserInformation.UserAgent;
  if (userAgent.IndexOf("MSIE 8.0") > 0)
  {
    return "Internet Explorer 8.0";
  }
  if (userAgent.IndexOf("MSIE 7.0") > 0)
  {
    return "Internet Explorer 7.0";
  }
  if (userAgent.IndexOf("MSIE 6.0") > 0)
  {
    return "Internet Explorer 6.0";
  }
  if (userAgent.IndexOf("MSIE 5.0") > 0)
  {
    return "Internet Explorer 5.0";
  }
  if (userAgent.IndexOf("Firefox") > 0)
  {
    return "Mozilla " + userAgent.Substring(userAgent.IndexOf("Firefox"), 100).Replace('/', ' ');
  }
  if (userAgent.IndexOf("Chrome") > 0)
  {
    return "Google " + userAgent.Substring(userAgent.IndexOf("Chrome"), userAgent.IndexOf("Safari") - userAgent.IndexOf("Chrome")).Replace('/', ' ');
  }
  if (userAgent.IndexOf("Safari") > 0)
  {
    return "Safari " + userAgent.Substring(userAgent.IndexOf("Version"), userAgent.IndexOf("Safari") - userAgent.IndexOf("Version")).Replace("Version/", String.Empty);
  }
  if (userAgent.IndexOf("Opera") > 0)
  {
    return userAgent.Substring(userAgent.IndexOf("Opera"), userAgent.IndexOf("(") - 2).Replace('/', ' ');
  }
  return "Unknown Browser";
}


* This source code was highlighted with Source Code Highlighter.

The code was successfully tested on IE and Chrome.

No comments: