Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current locale of Chrome

I am determining the current locale of the browser using this API:

var language = window.navigator.userLanguage || window.navigator.language;

This return "fr-FR" in IE, but it returns just "fr" in Chrome (and similarly for other locales).

Is there another API that will return "fr-FR" in Chrome as well?

We rely on this to load the appropriate culture files.

like image 285
Amar Avatar asked Sep 01 '14 13:09

Amar


People also ask

How do I check my browser locale?

To get the user's locale in the browser, access the first element of the languages property on the navigator object, e.g. navigator. languages[0] . The property returns an array of strings that represent the user's preferred languages.

What is a user locale?

A user locale specifies the default settings that a user wants to use for formatting dates, times, currency, and numbers.


1 Answers

Update:

As of Sept 2021 Chrome has pretty extensive support for the Intl library.

function getClientLocale() {
  if (typeof Intl !== 'undefined') {
    try {
      return Intl.NumberFormat().resolvedOptions().locale;
    } catch (err) {
      console.error("Cannot get locale from Intl")
    }
  }
}

Otherwise you can fallback to the window.navigator object:

Firefox and Chrome have a languages array on the navigator object. Normally the first element in that array is the users chosen locale (normally inherited from the OS settings)

var language;
if (window.navigator.languages) {
    language = window.navigator.languages[0];
} else {
    language = window.navigator.userLanguage || window.navigator.language;
}

The navigator.languages array in chrome for me is ["en-GB", "en-US", "en"] whereas navigator.language = "en-US", slightly different but important

like image 73
bm_i Avatar answered Sep 23 '22 00:09

bm_i