【问题标题】:How do you detect between a Desktop and Mobile Chrome User Agent?您如何在桌面和移动 Chrome 用户代理之间进行检测?
【发布时间】:2014-10-13 04:05:19
【问题描述】:

对于 Chrome 桌面扩展主页,我正在尝试检测用户是在 Android 上使用 Chrome for Desktop 还是 Chrome for Mobile。目前,下面的脚本将 Android Chrome 识别为与桌面版 Chrome 相同。在桌面 Chrome 上,它应该显示“chrome”链接;但是,如果有人使用 Android 版 Chrome,它应该显示“mobile-other”链接。

脚本:

<script>$(document).ready(function(){
    var ua = navigator.userAgent;
    if (/Chrome/i.test(ua))
       $('a.chrome').show();

    else if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile/i.test(ua))
       $('a.mobile-other').show();

    else
       $('a.desktop-other').show();
  });</script>

Chrome Android 用户代理:

Mozilla/5.0 (Linux; <Android Version>; <Build Tag etc.>) AppleWebKit/<WebKit Rev> (KHTML, like Gecko) Chrome/<Chrome Rev> Mobile Safari/<WebKit Rev>

【问题讨论】:

  • 如果您将 else if (/Android|... 更改为 if (/Android|... 会怎样?
  • @imtheman 显示两个按钮——“mobile-other”和“chrome button”
  • 好的,然后交换第一个ifelse if逻辑。

标签: javascript google-chrome browser-detection


【解决方案1】:

问题是用户代理总是有“Chrome”,无论是桌面版还是移动版。所以你必须先检查更具体的情况。

$(document).ready(function(){
    var ua = navigator.userAgent;

    if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i.test(ua))
       $('a.mobile-other').show();

    else if(/Chrome/i.test(ua))
       $('a.chrome').show();

    else
       $('a.desktop-other').show();
});

【讨论】:

  • iOS (v43.*) 上的当前 Chrome 移动版在其用户代理字符串中没有 Chrome。来自the docs:“iOS 版 Chrome 中的 UA 与 Mobile Safari 用户代理相同,使用 CriOS/ 而不是 Version/。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 2012-01-29
相关资源
最近更新 更多