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.