Friday, August 29, 2008

Lightweight device-detection

It is a simple C# function which will detect most mobile browsers.


public static bool isMobileBrowser()
{
string user_agent;
int mobile_browser;
Match match;
user_agent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
mobile_browser = 0;
string pattern = "(up.browserup.linkmmpsymbiansmartphonemidpwapphonewindows cepdamobileminipalm)";
Regex agentEx = new Regex(pattern, RegexOptions.IgnoreCase);
match = agentEx.Match(user_agent);
if(match.Success)mobile_browser = mobile_browser+1;
if(HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT"].IndexOf("application/vnd.wap.xhtml+xml")>=0
HttpContext.Current.Request.ServerVariables["HTTP_X_PROFILE"]!=string.Empty
HttpContext.Current.Request.ServerVariables["HTTP_PROFILE"]!=string.Empty)
{
mobile_browser = mobile_browser+1;
}
string[] mobile_agents = {
"w3c ", "acs-", "alav", "alca", "amoi", "audi",
"avan", "benq", "bird", "blac", "blaz", "brew",
"cell", "cldc", "cmd-", "dang", "doco", "eric",
"hipt", "inno", "ipaq", "java", "jigs", "kddi",
"keji", "leno", "lg-c", "lg-d", "lg-g", "lge-",
"maui", "maxo", "midp", "mits", "mmef", "mobi",
"mot-", "moto", "mwbp", "nec-", "newt", "noki",
"oper", "palm", "pana", "pant", "phil", "play",
"port", "prox", "qwap", "sage", "sams", "sany",
"sch-", "sec-", "send", "seri", "sgh-", "shar",
"sie-", "siem", "smal", "smar", "sony", "sph-",
"symb", "t-mo", "teli", "tim-", "tosh", "tsm-",
"upg1", "upsi", "vk-v", "voda", "wap-", "wapa",
"wapi", "wapp", "wapr", "webc", "winw", "winw",
"xda", "xda-"
};
int size = mobile_agents.Length;
string mobile_ua = user_agent.Substring(0, 4).ToUpper();
for(int i=0; i {
if( mobile_agents[i] == mobile_ua)
{
mobile_browser = mobile_browser+1;
break;
}
}
if(mobile_browser>0)
return true;
return false;
}

1 comment:

Anonymous said...

Hi,

you can make this faster/more efficient and easier to maintain if you turn the strategy around the other way.

See my post on "Not-Device" Detection.

http://MobileOnlineBusiness.com.au/blog?pb


roBman