[Drupal] How to switch to mobile theme when a Drupal website is accessed from a mobile device?

| | 1 min read

Nowadays most of the websites that are being built will have a mobile version also. One of the specific aspects we have to take care of with mobile sites is writing proper code to switch a drupal site to mobile website when the site is accessed from a mobile device. If you are trying to do the same thing then please follow below steps to solve your issue. Although this is written in the context of Drupal websites this should apply for other websites as well.

  • First of all include the two js files(Session.js and detectmobilebrowser.js) given below. This will detect the browser used.
  • Add the code given below to the page.tpl files of your desktop version theme.
    <script type="text/javascript">
          var url = window.location.href.split('?')[1];
          if (url == 'v=m') {
            Session.setVar('version', 'mobile');
          }
          var sessionHome = Session.getVar('version');
          var sessionMobile = window.name;
          var strSession = sessionMobile.toString();
          var sessionFound = strSession.search('mobile');
          if (!sessionHome) {
            if (sessionFound == -1){
              if (jQuery.browser.mobile) {
                var location_url = window.location;
                location_url = location_url.toString();
                var search_str = location_url.search(/http:\/\/m\.|http:\/\/www\.m\./i);
                if (search_str == -1) {
                  if (location_url.search(/http\:\/\/www/)!=-1) {
                    alert();
                    var mobile_url = location_url.replace("www.","m.");
                  }
                  else {
                    var mobile_url = location_url.replace("http://","http://m.");
                  }
                  window.location = mobile_url;
                }
              }
            }
          }
        </script>
  • Flush all caches and check with your mobile device it will automatically switch from 'www' to 'm'.

If all the above steps are followed correctly, your site will automatically switch to mobile website when accessed from a mobile device.

References:

  1. Detect Mobile Browser