Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect between a Desktop and Mobile Chrome User Agent?

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> 
like image 614
turmeric Avatar asked Aug 19 '14 22:08

turmeric


People also ask

How can I tell if I have a userAgent browser?

To detect user browser information we use the navigator. userAgent property. And then we match with the browser name to identify the user browser. Now call this JS function on page load, and this will display the user browser name on page load.

What is userAgent detection?

The User-Agent (UA) is a string contained in the HTTP headers and is intended for browser detection: to identify the device/platform of the visiting user, and can be used to determine appropriate content to return.

How do I find my Chrome userAgent?

Google Chrome Chrome's user agent switcher is part of its Developer Tools. Open them by clicking the menu button and selecting More Tools > Developer Tools. You can also use press Ctrl+Shift+I on your keyboard.


1 Answers

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(); }); 
like image 131
imtheman Avatar answered Sep 22 '22 21:09

imtheman