Detect User's Preferred Language and Google Translate Automatically
Solution 1
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
orwindow.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.
Solution 2
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>
Petar Stoyanov
Updated on July 26, 2022Comments
-
Petar Stoyanov almost 2 years
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?