Detect browser language preference in Firefox and Chrome using JavaScript

There are multiple ways to detect user's language preferences, but to do it pure client side was not an easy when you have to deal with Chrome and the reason was... ?

Well, Google Chrome does thing differently when it comes to navigator.language where you will expect that it will return you the user's language preference, but that's not the case. Google Chrome returns the value of navigator.language with the downloaded Google Chrome version, so if you downloaded the English Chrome then it will probably return en-US. Though, Firefox return the actual browser language preference that set by the user, so if I set my language preference in the setting page to Thai (th) then Firefox will return th even though my Firefox interface is in English.

Now, how I did I solve the problem when I had to work on localization before? Well, there weren't any other pure client side solution at the time that I can think of and I had to heavily rely on the server side and extract the language from Accept-Language in the request['headers'].

But! Finally, thanks to the open web and the super awesome web standard where people who make awesome thing for the web come together and agree on implementing navigator.languages.

navigator.languages returns a read only array of the user's preferred languages, ordered by preference with the most preferred language first. So, if I have my language in my setting in this order Thai (th), English (Canada) and English then navigator.languages should return ['th', 'en-CA', 'en'].

So, if you want to get the user's preferred language all you have to do now

navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)  

The above code will return "th". So, now you have pure client side javascript to get the user's language preference now!

As of now this works on: Chrome (v37), Firefox (v32) and Opera (v24), but not on: IE11

I hope this is helpful for some people who is looking for a pure client side solution and happy localization to all of you :D