Community

How to detect mobile devices in Drupal 6 theme template?

The challenge in implementing a responsive theme is to only insert the VIEWPORT tag for devices you wish to target. In my case, I want to add the tag for mobile-class devices, but not tablets.

I am trying to accomplish this with a conditional HEAD in the top of my theme template.php:

    if (getIsMobile()) {drupal_set_html_head('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">');}
   
    function getIsMobile()
    {
        $RE_MOBILE = '/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220)/i';

        $_isMobile = (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']) || preg_match($RE_MOBILE, $_SERVER['HTTP_USER_AGENT']));
        return $_isMobile;
    }

The string of user agents above intentionally omits iPad.

At first blush, this works OK, but it appears to "time out" in production mode. After some authencated activity like node editing, the VIEWPORT tag ceases to be included when viewing the site on an applicable mobile device. I haven't yet been able to determine the exact conditions under which this occurs, but I suspect this has to do with page caching (which is turned on to "normal"). Flushing all caches fixes the behaviour temporarily.

Can anyone suggest what may be faulty with this approach, or alternate approaches?

Comments

Using Modernizr

I came across a solution using Modernizr that may be of help

Ed

You can try this

rinku

nobody click here