Combining the multiple ways browsers are using to store the user's language, you get this function :
const getNavigatorLanguage = () => {
if (navigator.languages && navigator.languages.length) {
return navigator.languages[0];
} else {
return navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
}
}
We first check the navigator.languages
array for its first element.
Then we get either navigator.userLanguage
or navigator.language
.
If this fails we get navigator.browserLanguage
.
Finally, we set it to 'en'
if everything else failed.
And here's the sexy one-liner :
const getNavigatorLanguage = () => (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';