Detecting mobile browsers in Rails 3

后端 未结 3 551
逝去的感伤
逝去的感伤 2021-01-03 23:04

I\'m looking to do some mobile-specific layouts in my app, and have been researching ways to detect mobile browsers and serve mobile specific layouts.

I came across

相关标签:
3条回答
  • 2021-01-03 23:14

    The best way is to use some supported plugin/gem, like browser You're just unable to follow all browsers with their custom user_agents. For example Opera 11.50 has the following user_agent:

    Opera/9.80 (Android 2.3.7; Linux; Opera Mobi/ADR-1111021303; U; en-GB) Presto/2.9.201 Version/11.50
    

    It is totally unrecognizable with

    request.user_agent =~ /Mobile|webOS/ 
    
    0 讨论(0)
  • 2021-01-03 23:18

    There is actually a much simpler regular expression you can use. The approach is outlined in this Railscast and allows you to load different JS and define different page interactions for mobile devices.

    Essentially you end up with a function that simply checks that the user-agent contains 'Mobile' or 'webOS':

    def mobile_device?
      if session[:mobile_param]
        session[:mobile_param] == "1"
      else
        request.user_agent =~ /Mobile|webOS/
      end
    end
    
    0 讨论(0)
  • 2021-01-03 23:21

    Consider going away from the actual rails app on this one, and just change the css which is styling your page, that way you only have to rewrite the style sheet

    Basically the css can detect when the page width is small (ie mobile browser) like this

    <link rel="stylesheet" href="handheld.css" 
    media="only screen and (max-device width:480px)"/>
    

    and you can use this to have two different css handheld.css and normal.css for instance

    Resources

    Where I got that code snippet

    and the article that article references

    0 讨论(0)
提交回复
热议问题