I set 3 languages on Google Chrome, then I set the 2nd language English
for displaying the Google Chrome UI as shown below:
Then, I tried to get only the 2nd language English
used to display the Google Chrome UI because for users, I want to show my website in their languages used to display their browser UI by default and translation when they visit my website but I got the 1st language French
as shown below:
<script>
console.log(navigator.language); // fr
console.log(navigator.browserLanguage); // undefined
console.log(navigator.systemLanguage); // undefined
console.log(navigator.userLanguage); // undefined
</script>
So, are there any properties to get only the 2nd language English
used to display the Google Chrome UI?
2
Answers
window.navigator.languages
is an array of the users preferred languages in order of preference.window.navigator.language
is the language the web browser is using. So to get the 2nd language, you’d usewindow.navigator.languages[1]
EDIT: window.navigator.language may not always match the UI language of the browser (see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) – This is as close as you will get tho.
This is not possible, and you shouldn’t do it anyway. Apart from the existence of browsers without a UI or choosable UI language, your website is to be displayed inside a browser, as content. For that, the preferred website content language is the setting that is relevant – and also it’s the only one available to your website. In the huge majority of cases this is the same as the UI language, so it won’t make a difference to you, but in the cases where the user explicitly chose to display the browser UI in a different language than the visited websites, you should respect that decision. You’re making a website after all, not building a browser extension.
So use
navigator.language
, or for a best match from available languages, the prioritised list ofnavigator.languages
. There is no way to access the UI language setting.