Tuesday, February 14, 2012

Mobile Device Detection Without JavaScript

With the explosion of mobile devices in the form of phones, tablets, readers, etc there has been an increasing need to be able to detect if a user is on a mobile device and to format web content appropriately for them.  There are several methods for detection such as using JavaScript or CSS.  The following article does a good job summarizing the various techniques.

http://webdesign.about.com/od/mobile/a/detect-mobile-devices.htm

The one that seemed the most flexible and future proof is a project called wurfl.  Essentially what it is is a user community maintained list of devices and their capabilities that is continuously updated.  The list is in the form of an xml file that is read by the underlying platform at runtime.  The only downside to this file is that it must be downloaded on a regular basis to maintain a listing of the current devices.  However, this is much preferable to having to write out a long list of things in JavaScript in order to do the detection.

The wurfl project is at http://wurfl.sourceforge.net/

It's pretty simple to use as well, for example to detect if a device is a mobile device or not from a JSP you would execute the following code:

    WURFLHolder wurflHolder = (WURFLHolder) getServletConfig().getServletContext()
            .getAttribute("net.sourceforge.wurfl.core.WURFLHolder");

    WURFLManager wurfl = wurflHolder.getWURFLManager();

    Device device = wurfl.getDeviceForRequest(request);

    Boolean result = new Boolean(device.getCapability("is_wireless_device"));

    if ( result ) {
        System.out.println("This is a mobile device!");
    }
    else {
        System.out.println("This is not a mobile device!");
    }