↑
Main Page
Detecting language using JavaScript
Detecting language using JavaScript
In Chapter 5, “JavaScript in the Browser,” you were introduced to the
navigator
object and its proper-
ties. One of the properties that has not been discussed in detail is the
language
property, which returns
the language and country code in which the browser is currently operating (for example, “en-us” for
United States English):
var sLang = navigator.language; //won’t work in IE
Mozilla, Opera, and Safari/Konqueror all support this property, but Internet Explorer does not.
Instead, Internet Explorer provides three properties:
browserLanguage
(indicates the language being
used by the browser),
userLanguage
(essentially identical to
browserLanguage
), and
systemLanguage
(indicating the language of the operating system). The
userLanguage
property is essentially the same as
language
, so you can make a simple addition to the previous code to detect the language for all
browsers:
var sLang = navigator.language || navigator.browserLanguage;
Using this code, you can determine if someone is viewing your page from a browser with an unsupported
language setting and take appropriate action, such as redirecting the visitor to a more appropriate page:
if (sLang.toLowerCase() == “fr”) {
document.location.replace(“index_fr.htm”);
}
This code checks to see if the language is French (represented as
“fr”
), and if so, it redirects to another page.
Strategies
The most important step in internationalizing your JavaScript is to avoid hard-coded strings. For example,
don’t do this:
alert(“The date you entered is incorrect.”);
In this example, the string
“The date you entered is incorrect.”
is hard-coded. When a value is
hard-coded, its value cannot be changed without directly editing the line that uses it. Compare this with
the following example:
var sIncorrectDateMessage = “The date you entered is incorrect.”;
//more code here
alert(sIncorrectDateMessage);
You may have noticed that this code uses
toLowerCase()
on the language string.
This is necessary because capitalization is not consistent across browsers. Some
report United States English as
“en-us”
, whereas others use
“en-US”
.
569
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 569
Free JavaScript Editor
Ajax Editor
©
→