Tag Archives: Regex

Detecting mobile browser in ASP.Net

Detecting mobile browsers can be a bit of pain.  Whilst it is relatively easy to get browser information through the User Agent string, it is not such a simple task to identify the client device type.  There is no defined property within the user agent field that says I’m a mobile device.  User Agent values differ widely between devices and browsers, so it is necessary to use some less than elegant detection code.

I recently added this detection functionality to the Camino CMS Framework, and Calzada’s preferred method is using regular expressions.  After some playing, we came up with the following regex:

(?i)(android(?:.+mobile)|applewebkit.+(?:\(KHTML, like Gecko){1}|avantgo|blackberry|blazer|docomo|elaine|fennec|htc|kindle|lge|linux.+armv|mmp|mms(?:.+midp){1}|mobile|mot(?:.+midp){1}|nintendo.+(?:3ds|wii)|nokia|nook|opera(?:.+mini|.+mobi){1}|palm|polaris|phone|ppc|psp|samsung|sec|sony|symbian|tablet|up\.browser|vodafone|wap|webos|windows(?:.+ce|.+mobile){1}|xda|xiino

A simplified ASP.Net detection code would look something like this:

Function IsMobileBrowser() As Boolean
Dim regex As New Text.RegularExpressions.Regex("(?i)(android(?:.+mobile)|applewebkit.+(?:\(KHTML, like Gecko){1}|" & _
"avantgo|blackberry|blazer|docomo|elaine|fennec|htc|kindle|lge|linux.+armv|mmp|mms(?:.+midp){1}|mobile|mot(?:.+midp){1}|" & _
"nintendo.+(?:3ds|wii)|nokia|nook|opera(?:.+mini|.+mobi){1}|palm|polaris|phone|ppc|psp|samsung|sec|sony|symbian|tablet|" & _
"up\.browser|vodafone|wap|webos|windows(?:.+ce|.+mobile){1}|xda|xiino", Text.RegularExpressions.RegexOptions.IgnoreCase)
Return regex.IsMatch(HttpContext.Current.Request.ServerVariables("http_user_agent").ToString)
End Function

There are a couple of key points to bear in mind with this method:

  1. It is not perfect.  No matter how you tailor and tweak the regular expression, you are inevitably going to get some false positives and false negatives.
  2. This is not a write and forget function.  As the number of mobile devices and manufacturers proliferate, the accuracy of the regular expression will diminish.  To compensate, it is necessary to regularly review, test and update where required.  To ensure that this is done, this process has been added this to the Camino development lifecycle.
  3. Not all mobiles or mobile users may wish to use mobile variant of a website.  Do bear in mind that some tablets have a sufficiently large screen to view the normal version of a website.
I am aware that this is not an elegant nor wholly accurate solution, and there are plenty of programmers out there that will view it as a kludge, but in many ways it is a product of its’ ingredients.  Until such time when all browsers will provide a property that simply states I’m running on a mobile device, then this will have to do.