Detect User's Preferred Language and Google Translate Automatically

Petar Stoyanov picture Petar Stoyanov · Feb 12, 2013 · Viewed 13.1k times · Source

I use this script in my site for translation

<div id="google_translate_element" align="center"></div>  
<script type="text/javascript">
    function googleTranslateElementInit() {
        new google.translate.TranslateElement({
        pageLanguage: 'auto',
        autoDisplay: false,
        layout: google.translate.TranslateElement.InlineLayout.SIMPLE
        }, 'google_translate_element');
    }
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

It is working just fine :) But is there a way to detect the user ip and auto translate when a user go in to my site?

Answer

Shervin picture Shervin · Apr 12, 2013

Although you can use IP-based location detection (see this answer), but it's neither reliable nor makes you wiser about user's preferred languages (e.g. users travelling abroad, etc.).

Websites with heavy international traffic use various parameters to decide in which language the content should be presented. Some of these parameters:

  • Accept-Language HTTP header which is discussed in detail here.
  • Values of properties window.navigator.language or window.navigator.userLanguage (for IE)
  • IP-based location detection data checked against CLDR to provide you with common languages in that territory.

MediaWiki extension, UniversalLanguageSelector, uses these factors as well as stored user preferences to provide a list of common languages for each user. See getFrequentLanguageList().

W3C also has some recommendations.