检测网页浏览器或手机显示链接
问题描述:
我正在写一个rails应用程序,需要为移动用户提供不同的链接给普通的网页浏览器用户。例如,如果用户在移动我想显示:检测网页浏览器或手机显示链接
<a href="instagram://user?username=<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>
如果用户是在浏览器上我想显示:
<a href="http://instagram.com/<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>
什么是做到这一点的最好方法是什么?由于
答
浏览器数据来自于user_agent
对象的形式:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
helper_method :mobile?
private
def mobile? # has to be in here because it has access to "request"
request.user_agent =~ /\b(Android|iPhone|iPad|Windows Phone|Opera Mobi|Kindle|BackBerry|PlayBook)\b/i
end
end
这将允许你使用你的看法如下:
#app/views/controller/view.html.erb
<% if mobile? %>
... do something for mobile
<% else %>
... do something else
<% end %>
诚实,我不知道为什么人们对他们的移动界面工作进行硬编码。如果您正确使用CSS media queries,则不应该对这些文件有任何问题,尽管您的情况看起来需要服务器端条件。
答
我建议你使用像引导或基金会的前端工作。这些框架允许您定位到移动视图和桌面视图。
答
我猜测你想实现deep linking。为此,我建议你使用deeplink.me。但是,如果你想要这样做的方式,那么有一个名为browser
的宝石。以下代码将帮助您进行设置。
的Gemfile:
gem 'browser'
然后在
application_controller.rb:
class ApplicationController < ActionController::Base
before_filter :get_browser
def get_browser
@browser = Browser.new(:ua => request.user_agent)
end
end
在你的意见
最后,你可以这样做:
<% if @browser.mobile? %>
<a href="instagram://user?username=<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>
<% else %>
<a href="http://instagram.com/<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>
<% end %>
+0
真棒,要试试这个! – fixulate
我使用的引导,但我仍然需要以确定其移动设备来显示不同的链接...需要这个答案详细信息,我觉得:) – fixulate