Read more

Detect mobile or touch devices on both server and client

Henning Koch
January 04, 2012Software engineer at makandra GmbH

There is a better maintained regular expression to be found on detectmobilebrowsers.com.

Although it's tempting flirt with detecting mobile/touch devices with CSS media queries or Javascript feature detection alone, this approach will be painful when heavily customizing a feature beyond just tweaking the looks. Eventually you will want want the same detection logic to be available on both server and client side.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

This card shows how to get a Ruby method touch_device? for your Rails views and a method TouchDevice.isPresent() for your Javascripts.

Note that we are detecting touch devices by grepping the user agent, and the keyword list we are sniffing for sure is lacking many unpopular phones.


In your ApplicationHelper:

def touch_device?
  user_agent = request.headers["HTTP_USER_AGENT"]
  user_agent.present? && user_agent =~ /\b(Android|iPhone|iPad|Windows Phone|Opera Mobi|Kindle|BackBerry|PlayBook)\b/i
end

In your layout:

%html
  %body{ :class => 'touch_device' => ('true' if touch_device?)}

In your application.js:

var TouchDevice = (function() {

  var presence = null;

  function isPresent() {
    if (_.isNull(presence)) {
      presence = $('body').is('.touch_device');
    }
    return presence;
  }

  return { isPresent: isPresent };

})();
Posted by Henning Koch to makandra dev (2012-01-04 12:36)