The mobile world changes almost daily. Expanding on http://scottwb.com/blog/2012/02/23/a-better-way-to-add-mobile-pages-to-a-rails-site/ which is sorta old -- what do you guys think of this mobile and tablet detection scheme?
Use case: The mobile and desktop versions of my Rails app are very different. Although they share the majority of views, JS and CSS (using media queries where applicable), there are cases where I need mobile-only and desktop-only views, JS and CSS.
Code changes
All tablets should be treated as mobile.
- Android tablet support: How do detect Android Tablets in general. Useragent? -- added
android
- Windows tablet support: how to identify if user agent is windows 8 tablet? -- added
touch
- Proper webOS support: What's the best way to detect a webOS tablet with jQuery / plain JS -- added
hpwos
Above Android tablet thread mentions this for mobile:
/iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/
And this for tablet:
/ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/
I reckon, however, that only the below should be necessary?
/mobile|android|touch|webos|hpwos/
application_controller.rb
def mobile?
if session[:mobile_override]
session[:mobile_override] == "1"
else
request.user_agent.downcase =~ /mobile|android|touch|webos|hpwos/
end
end
helper_method :mobile?
layout.html.erb
<% if mobile? %>
<p>Mobile detected!</p>
<% end %>
application.js
var isMobile = false;
if(/mobile|android|touch|webos|hpwos/i.test(navigator.userAgent.toLowerCase())) {
isMobile = true;
}
if(isMobile) {
console.log('Mobile detected!')
}