Possible Duplicate:
JavaScript for detecting browser language preference
I want to detect the language of the browser that is entering my site, if it's En or Fr. So I can redirect to the En page or the other page.
Also, can I detect mobile language?
Possible Duplicate:
JavaScript for detecting browser language preference
I want to detect the language of the browser that is entering my site, if it's En or Fr. So I can redirect to the En page or the other page.
Also, can I detect mobile language?
Try this script to get your browser language
<script type="text/javascript">
var userLang = navigator.language || navigator.userLanguage;
alert ("The language is: " + userLang);
</script>
navigator.language || navigator.userLanguageacceptedlanguages.js which is entirely javascript and browser compatible covering all the cases: github.com/leighmcculloch/acceptedlanguages.jsAt this point navigator.userLanguage has long since been deprecated, so you can get the user's language tags via navigator.language directly:
const lang = navigator.language;
If you need more granular information, you can create an Intl.Locale object:
const locale = new Intl.Locale(navigator.language);
switch (locale.language) {
case 'en':
// do something for English
break;
case 'fr':
// do something for French
break;
...
}
In my original answer from 14 years ago, I mentioned that language detection should be done on the server. While I don't think that's fully wrong, it's also not fully right either. A lot has changed in the last 14 years.
It's worth calling out the existence of the Accept-Language header in browser http requests, and that for some payloads it is probably beneficial to perform translation server-side with the initial request to avoid additional unnecessary round-trips. However, there are also situations where it's entirely valid to use the user's language in client-side scripts, so use your best judgement.
HTTP_ACCEPT_LANGUAGE