33

For a Chrome Desktop Extension home page, I'm trying to detect whether a user is using Chrome for Desktop or Chrome for Mobile on Android. Currently the script below identifies Android Chrome the same as Desktop chrome. On desktop Chrome it should show "chrome" link; however, if someone is on Chrome for Android, it should show the "mobile-other" link.

Script:

<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 User Agent:

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

2 Answers2

53

The problem is the user agent will always have "Chrome" whether it is the desktop or mobile version. So you have to check the more specific case first.

$(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();
});
imtheman
  • 4,713
  • 1
  • 30
  • 30
  • 2
    The current Chrome mobile version on iOS (v43.*) does not have `Chrome` in its user agent string. From [the docs](https://developer.chrome.com/multidevice/user-agent): "The UA in Chrome for iOS is the same as the Mobile Safari user agent, with CriOS/ instead of Version/." – Tim Jul 08 '15 at 10:36
0

Minimized test using Alert

// userAgent
const userAgent = navigator.userAgent;
console.log(userAgent);
if(/Chrome/i.test(userAgent)) {
alert('DESKTOP CHROME USER');
}
Hugo Barbosa
  • 85
  • 1
  • 4