Detect Google Website Translator change of language

匆匆过客 提交于 2019-12-22 10:57:23

问题


I'm using the Google Website Translator on my website to let the user translate the site on the fly. Using this code:

    function googleTranslateElementInit() {
        new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar,de,el,en,es,fr,it,ja,ko,nl,ru,zh-CN', layout: google.translate.TranslateElement.FloatPosition.BOTTOM_RIGHT}, 'google_translate_element');
    }

This works great, only thing now is that I need to know which language the user has actually selected. I want to detect both when the user manually selects a language and also when the translator makes an automated translation, as its enabled to do automatic translations based on the browser settings.

What I want to do is to add an event listener to when the language is changed. I.e. not only when the user manually sets the language but every time the translator actually does a translation. E.g. when the translation starts or finishes or when the page "refreshes" to show the new language.

I need to collect this information and send it to the server to know what language to use for e-mails that are sent to the user at a later stage. As this information is gathered from multiple places, I don't want to manually check the selected language every time I required the information, but to add an event listener that detects the language changing and triggers an AJAX method to save the information in session on the server.

Thanks!


回答1:


When the user manually selects a language (changes the value of the selectbox) you might get the language chosen with

$('.goog-te-combo').on('change',function(){
       language = $("select.goog-te-combo option:selected").text();
        alert(language);
    });

Fiddle

In case when your page refreshes and the translator translates your page, you could get the current language that is being used by using a setTimeout. This isn't perfect, but it certainly helps mate.. :)




回答2:


You can use setInterval to periodically check to see if the language changed:

var translatedText='';
var interval=setInterval(function(){
   var el=document.getElementsByClassName('goog-te-menu-value')[0];  
   if(el && el.innerText!==translatedText){
        translatedText=el.innerText;
        console.log('changed');
    }
},200);

Working JS Bin: http://jsbin.com/neteqihage/1/



来源:https://stackoverflow.com/questions/27935450/detect-google-website-translator-change-of-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!