0

I know this is bad practice and feature recognition should be the way to go in terms of building the website. However that is not my use case.

I have different distributions of my browser extension and I would like to change the download button based on their current browser.

I've tried using navigator.userAgent, that has proven to be quite useless as most browsers have set all popular user agents. For example chrome has this.

navigator.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36"

I've seen many websites have this feature on their download buttons. How is this done properly?

EDIT: I've now learned the history of why "Mozzila/X.X" is at the start of the userAgent string. Apologies for the misunderstanding.

peso
  • 33
  • 1
  • 6
  • how is it useless? Chrome does say "Chrome"... userAgents are enough, you just need to pay close attention. – dandavis Apr 07 '16 at 20:34
  • they could be clearer, i'll admit. the most common gotcha is "Safari" and "Chrome". if it has "Chrome", it's not safari, make sure to handle that and the rest are semi-easy. – dandavis Apr 07 '16 at 20:46
  • @dandavis, I was assuming Mozilla meant firefox. Now I see that it isn't. – peso Apr 08 '16 at 16:56

1 Answers1

2

You can detect browsers in multiple ways.

For Chrome, apart from making a regex on the navigator.userAgent:

var isChrome = /Chrome/.test(navigator.userAgent);

You can also make a check on:

var isChrome = !!window.chrome && !!window.chrome.webstore;

I suggest you to see this answer for further details.

You should also consider using Modernizr.js for browser detection.

Community
  • 1
  • 1
Jonathan Argentiero
  • 5,687
  • 8
  • 29
  • 34
  • that accepted answer is terrible... it's browser sniffing in another manner. in a less-reliable manner at that; looking for common side-effects that could expire with a version update or careless script... – dandavis Apr 07 '16 at 20:41
  • I also don't like that implementation. To me if you want the most solid way to detect a browser is relying on [Modernizr.js](https://modernizr.com/). Otherwise the remaining solutions are regex on `navigator.appName`, `navigator.appVersion` and `navigator.userAgent` or those ugly hacks. – Jonathan Argentiero Apr 07 '16 at 20:45
  • i don't see why devs are quick to dismiss userAgent; it's exactly what's supposed to be used. if 0.02% of users change theirs, so be it; they can disable JS too, so WTH. pick your battles. – dandavis Apr 07 '16 at 20:48