Friday, 6 July 2007

Detecting a Mobile / WAP Browser in code (using User-Agent)

I recently got a task to create a simple terms and conditions page that would be sent in a link via our SMS API as a SMS or WAP Push message. The idea being that the phone can browse to the URL via the WAP browser or alternatively use a browser on their PC or MAC. I wanted some sort of simple switch, to display a WAP WML page for a mobile browser or a full html page for a PC or MAC browser. I had a quick look at the HTTPRequest class and found a Request.Browser.IsMobileDevice bool flag. This would be perfect... if it worked! Having tested the flag with several makes and models of phone, it seemed to only work on a selection. After doing a bit of an investigation I found that all the mobile browsers I tested with had similar user-agent values ( Request.Headers["User-Agent"] ). They all contained a value "MIDP", e.g. Nokia6230i/2.0 (03.25) Profile/MIDP-2.0 Configuration/CLDC-1.1. As you can see, we can also grab the device model and manufacturer from the user-agent also. MIDP, or Mobile Information Device Profile. MIDP, combined with the Connected Limited Device Configuration (CLDC), is the Java runtime environment for today's mobile information devices (MIDs) such as phones and entry level PDAs. I found a useful MIDP device list at Club Java. Searching for midp in the user-agent should work pretty well as far as my tests show. And you can also check for additional values supplied in the HTTP request to ensure the redirection works when required. .Net code sample:
bool isWMLBrowser = false;
if (Request.Headers["User-Agent"] != null)
         = Request.Headers["User-Agent"].ToLower().Contains("midp");

if (!isWMLBrowser)
   // Redirect to HTML page
   // Redirect to WML WAP page
Any one else have any other bright ideas?


Kilimanjaro said...

This has worked nicely for me, thanks!

Anonymous said...

Thanks, Just what I was looking for!