How to getting browser current locale preference using javascript?
Solution 1:
The following properties exist on the navigator
object (which can also be known as clientInformation
on IE but there's no reason ever to use that name):
-
language
(non-IE, browser install language) -
browserLanguage
(IE, browser install language) -
userLanguage
(IE, user-level OS-wide language setting) -
systemLanguage
(IE, OS installation language)
But! You should never use any of these properties! They will be the wrong language in many cases.
None of them reflect the language settings the user actually gets to configure in the browser's ‘preferred languages’ UI, and they are difficult-to-impossible for users to change. You will cause big frustration by using any of these values without an additional easy manual way to switch languages.
The correct place you should sniff to decide what language to use by default, as configured by the normal browser UI, is the Accept-Language
header passed to your server in the HTTP request. This is a ranked list of preferred languages from which you can pick, and it's what ASP.NET uses to guess an automatic client Culture, if you use that.
Unfortunately, this property is not available from JavaScript!
What you typically do is use your server side to parse the Accept-Language
header and choose a single appropriate language to use from it. In ASP.NET you can get a pre-sorted list from HttpRequest.UserLanguages and pick the first that you like.
You then spit that language name out into a <script>
element to pass the language information to the client side.
Solution 2:
Try this:
var l_lang;
if (navigator.userLanguage) // Explorer
l_lang = navigator.userLanguage;
else if (navigator.language) // FF
l_lang = navigator.language;
else
l_lang = "en";
Source: http://forums.digitalpoint.com/showthread.php?t=631706
Solution 3:
navigator.languages
is an array and contains all the selected languages in order. And only works for Chrome and Firefox.
It is not the same as navigator.language
and by that I mean that navigator.language
does not necessarily match navigator.languages[0]
.
Just to be clear.