The MDN documentation says that window.navigator.userAgent is deprecated and should not be used. If I want to collect the users browser and os data for analytics (not feature detection), what should I use instead?
The user agent string is becoming meaningless and extremely unreliable.
You should not use user agent string, rather you should use feature detection. If you need to use feature X, test to see if X is available.
But to also answer your question directly, there is no JS alternative.
Browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable.
For example:
- In Firefox, you can change the preference general.useragent.override in about:config. Some Firefox extensions do that; however, this only changes the HTTP header that gets sent, and doesn't affect browser detection performed by JavaScript code.
- Opera 6+ allows users to set the browser identification string via a menu
- Microsoft Internet Explorer uses the Windows registry
- Safari and iCab allow users to change the browser user agent string to predefined Internet Explorer or Netscape strings via a menu.
Source
I think, that they are trying to remove completely this feature from JavaScript.
Update:
Object-Oriented JavaScript, 2nd Edition: It's better not to rely on the user agent string, but to use feature sniffing (also called capability detection) instead. The reason for this is that it's hard to keep track of all browsers and their different versions. It's much easier to simply check if the feature you intend to use is indeed available in the user's browser. For example have a look at the following code:
if (typeof window.addEventListener === 'function') { // feature is supported, let's use it } else { // hmm, this feature is not supported, will have to // think of another way }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With