5.8 Detecting the Browser Written Language

NN 4, IE 4

5.8.1 Problem

You wish to direct users automatically to a path in your web site tailored for a specific written language.

5.8.2 Solution

Version 4 and later browsers provide properties of the navigator object that let you read the code for the native language for which the user's browser was developed. Unfortunately, the property names are different for each browser, so you must perform some object property detection in the process. The solution below assumes that all users will be shunted to the English page unless their browsers indicate that the native language is German:

// verify browser language
function getLang(type) {
    var lang;
    if (typeof navigator.userLanguage != "undefined") {
        lang = navigator.userLanguage.toUpperCase( );
    } else if (typeof navigator.language != "undefined") {
        lang = navigator.language.toUpperCase( );
    return (lang && lang.indexOf(type.toUpperCase( )) =  = 0)
location.href = (getLang("de")) ? "de/home.html" : "en/home.html";

The case conversions eliminate potential differences in the case of the letters returned by the language-related properties of browsers. In the end, the return statement performs string equality testing on all uppercase letters (see Recipe 1.3 and Recipe 1.4).

5.8.3 Discussion

Language codes consists of a primary two-letter code indicating the basic language. An optional two-letter subcode may also be used to identify a country or region for which the primary language is tailored ("en-us" for United States English). Therefore, you cannot always rely on the navigator object's language-related property returning only a two-letter code. But since the primary code always comes first, you can look for the code being at the beginning of whatever string is returned by the property. Also, be sure to force the case of the values so that your eventual comparison operation works on a level playing field, regardless of the case of the returned data. Nonscriptable browsers will still need links on the page to provide manual selection of the desired language path through the site. Common two-letter primary codes are cataloged in ISO-639 (an excerpted list of codes is available at http://www.ietf.org/rfc/rfc1766.txt).

5.8.4 See Also

Recipe 5.1 and Recipe 5.2 for browser brand and version detection; Chapter 1 for string parsing.