Detect User's Preferred Language and Google Translate Automatically

佐手、 提交于 2019-11-28 06:05:41
Shervin

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.

This script shows the translation drop-down box only for people with English not set as their primary or only language, and hides it when English users view the page - it is coded for English pages using the en in the google code.

It uses the first 2 characters of the language only to avoid checking for the many variants of English like en-US, en-tt etc - they all begin with en.

This could easily be adapted to detect pageLanguage and compare it with the user's preferred language(s). The use of navigator.languages is important because this is used on newer browser releases, see cross-browser compatibility explained

<div id="google_translate_element"></div>
<script type="text/javascript">
var userLang = navigator.language || navigator.userLanguage || navigator.languages; 
if (userLang.substr(0,2) != "en"){
  function googleTranslateElementInit() {
    new google.translate.TranslateElement({pageLanguage: 'en', layout: 
    google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element');
   }
 }
else { 
  document.getElementById("google_translate_element").style.display="none";
  }
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!