0

Is there any way to detect a client's computer language? I have developed my website in 2 languages: English and German. If people in Germany open my web site it should open the German version, otherwise it will open the English version for any other country of origin.

I've tried to searching Google and there's only a detect browser language feature. Is this the best way?

Ps. I am not asking for your code here, just suggestions on how to accomplish this, but if you guys want to show me real examples it would be appreciated!

leigero
  • 3,233
  • 12
  • 42
  • 63
MANGA
  • 27
  • 7
  • 1
    A common approach is to handle this on the server side and check the IP address of the client. – Felix Kling Aug 12 '13 at 11:02
  • 1
    See http://stackoverflow.com/questions/8601837/how-to-detect-users-language-the-simple-way, http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference, http://stackoverflow.com/questions/8199760/how-to-get-the-browser-language-using-java-script – PiLHA Aug 12 '13 at 11:03

2 Answers2

2

In recent browsers, navigator.language is what you want:

if (navigator.language == "de") {
    alert("Guten Tag!");
} else {
    alert("Good Morning!");
}
Koterpillar
  • 7,883
  • 2
  • 25
  • 41
1

Use the Accept-Language header. This is the language that the user has explicitly requested by setting it up in the browser options (defaulting to the browser's installation language otherwise). The header can contain multiple languages with ratings eg:

fr,ja,de-AT;q=0.8,de;q=0.6

so you would want to pick the highest-rated (or first-listed if tied) of languages beginning ‘en’ and ‘de’.

Unfortunately the Accept-Language header is not readily accessible to JavaScript.

In recent versions of Firefox navigator.language will give you the highest-rated language from that list. Unfortunately that doesn't help you if the user has requested languages in the order “French, German”, as you'll only see the fr.

In other browsers, it gives you the browser install language, which is a reasonable guess but not as good as the language the user has actually asked for. On IE browserLanguage is the same thing, and there's also userLanguage and systemLanguage which relate to the Windows locale, which is usually a much worse guess.

So if you want the “highest rated user-configured language out of English and German” the best thing to do is read and parse the Accept-Language header at the server side, then return that language in a string to the JS code. http_negotiate_language is a PHP function that will help you parse the header (from $_SERVER['HTTP_ACCEPT_LANGUAGE']) properly.

Whatever you do, provide a manual method for switching languages because even the best guess can be wrong.

bobince
  • 528,062
  • 107
  • 651
  • 834