Detecting a Mobile Browser on the Server in your Rails app

the following code was extracted from my Mobile Ruby on Rails Web App Demo, which was intended as a very simple Mobile Ruby on Rails Web Application (Web App) which uses Ruby 1.9.2, Ruby on Rails 3.0.7 and jQuery Mobile (specifically the jQuery Mobile 1 Alpha 4.1 maintenance release in May 2011.)

The code does a mobile client detection, server side, in the Application Controller by parsing the HTTP_USER_AGENT, or “User-Agent” HTTP header. This is sometimes called “UA sniffing” or User Agent Sniffing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ApplicationController < ActionController::Base
  protect_from_forgery
 
    before_filter :set_browser_type
 
 def set_browser_type
   @browser_type = detect_browser
 end
 
  private
   
  MOBILE_BROWSERS = ["playbook", "windows phone", "android", "ipod", "iphone", "opera mini", "blackberry", "palm","hiptop","avantgo","plucker", "xiino","blazer","elaine", "windows ce; ppc;", "windows ce; smartphone;","windows ce; iemobile", "up.browser","up.link","mmp","symbian","smartphone", "midp","wap","vodafone","o2","pocket","kindle", "mobile","pda","psp","treo"]

  def detect_browser
    agent = request.headers["HTTP_USER_AGENT"].downcase
 
    MOBILE_BROWSERS.each do |m|
      return "mobile" if agent.match(m)
    end
    return "desktop"
  end
 
 
end

The hard part is the Mobile browser user agent list. Sadly I dont remember where I got the original list and then added in the several more recent agent names, but the nature of such things is that it is always out of date! ZYTRAX has a good list of Mobile Browser ID (User-Agent) Strings.

It is used in a ERB view like this :

1
< %= "You don't Look like a Moblie Client :(" if @browser_type != "mobile"  %>

You could also use similar code to control whether to add or change the javascript and css being used, the size of images to use, or additional page elements on the view. In the controller such code could redirect users to the mobile views, if the non mobile views are very different.

If you needed more detailed parsing of the Agent string then Kevin Elliott’s Agent Orange looks really good, and goes beyond just mobile browser detection.

One thought on “Detecting a Mobile Browser on the Server in your Rails app

  1. Pingback: Doing Conditional Comments for your Internet Explorer css fixes better, with HTML top tag classes | False Positives

Leave a Reply