Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If window.navigator.userAgent is deprecated, what should I use instead? [duplicate]

Tags:

javascript

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?

like image 467
blub Avatar asked Apr 27 '16 17:04

blub


2 Answers

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.

like image 57
Mate Hegedus Avatar answered Oct 05 '22 19:10

Mate Hegedus


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
}
like image 24
Ali Mamedov Avatar answered Oct 05 '22 19:10

Ali Mamedov