【问题标题】:Check device type via user_agent (rails)通过 user_agent (rails) 检查设备类型
【发布时间】:2015-09-16 06:56:07
【问题描述】:

我想知道我的用户是否正在使用我的 rails 应用程序浏览页面

  • 平板电脑或
  • 移动设备或
  • 台式电脑

我研究了许多不同的解决方案。以下是我的最爱:

  1. ua-parser gem:https://github.com/ua-parser/uap-ruby,看起来很干净,但不幸的是,当我使用parsed_string.device 时,它总是绘制Other - 我可以很好地检测操作系统和浏览器。
  2. 从头开始编写

从头开始写作最终是这样的:

if request.user_agent.downcase.match(/mobile|android|iphone|blackberry|iemobile|kindle/)
  @os = "mobile"
elsif request.user_agent.downcase.match(/ipad/)
  @os = "tablet"
elsif request.user_agent.downcase.match(/mac OS|windows/)
  @os = "desktop"
end

但是,我错过的是用户代理“设备”定义的完整文档。

例如: 如果我的用户在平板电脑/移动设备或台式机上浏览,我需要查看哪些模式?我不能只是猜测和检查,例如ua-parser 正则表达式也没有帮助我(非常复杂):https://github.com/tobie/ua-parser/blob/master/regexes.yaml

有什么简单的方法可以解决我的问题吗? 谷歌分析是如何做到的?我试图研究但找不到。他们还展示设备(台式机/平板电脑/移动设备)。

【问题讨论】:

  • 试试browser。很多方面都比ua-parser
  • 看起来很有希望,谢谢

标签: ruby-on-rails user-agent


【解决方案1】:

browser gem 有一个 suggestion 来执行此操作,但在添加之前,您仍然可以使用 gem 通过使用 browser.device? 来解决它

【讨论】:

    【解决方案2】:

    我正在寻找第二个选项,因为我需要它尽可能精益求精。 User-Agent 字符串中有很多我不需要的信息。而且我不想要一个试图解析它的函数。很简单:机器人、台式机、平板电脑、移动设备和其他。

    阅读内容有点多,但我正在寻找使用 this extensive list 的关键字。

    到目前为止,以下关键字似乎对我有用。这是 php 中的正则表达式,但你会明白的。

    //try to find crawlers
    //  https://developers.whatismybrowser.com/useragents/explore/software_type_specific/crawler/
    if (preg_match('/(bot\/|spider|crawler|slurp|pinterest|favicon)/i', $userAgent) === 1)
      return ['type' => 'crawler'];
    
    //try to find tablets
    //  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/tablet/
    //  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/ebook-reader/
    if (preg_match('/(ipad| sm-t| gt-p| gt-n|wt19m-fi|nexus 7| silk\/|kindle| nook )/i', $userAgent) === 1)
      return ['type' => 'tablet'];
    
    //try to find mobiles
    //  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/mobile/
    //  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/phone/
    if (preg_match('/(android|iphone|mobile|opera mini|windows phone|blackberry|netfront)/i', $userAgent) === 1)
      return ['type' => 'mobile'];
    
    //try to find desktops
    //  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/computer/
    if (preg_match('/(windows nt|macintosh|x11; linux|linux x86)/i', $userAgent) === 1)
      return ['type' => 'desktop'];
    
    return ['type' => 'other'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-16
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多