How to translate injected text using Google Translate web plugin?

1.2k views Asked by At

I have implemented the the Free google translate plugin into my website but after I inject text into the page using JS it doesn't translate the newly injected text.

I can't delay the translation process after getting the text because user actions cause the text injection.

I have seen this question: https://stackoverflow.com/questions/36100201/how-i-can-call-google-translate-using-function-on-submit

But it has no answer and not the exact question that I want to ask.

  1. Is there any method to send callback function to google's translation JS function?
  2. What are the limits of using Google's website translation plugin ?
1

There are 1 answers

0
Pini Cheyni On

Google Translate Web Plugin translates automatically all the visible text on the page as you scroll the page.

  • I have found no limits for using Google Translate web Plugin.
  • Newly injected text (using JavaScript) should be translated automatically.
  • I was unable to find callback mechanism inside of google's API but I have found a workaround that should work (Using event Listener) as explained below.

Implement callback mechanism for changing language in Google Translate web plugin:

//Google Translate
function googleTranslateElementInit() {
    new google.translate.TranslateElement({
        pageLanguage: 'iw',
        //layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
        includedLanguages: 'ar,en,fr,hu,ru',
    }, 'google_translate_element');
}
  • I have commented out the layout to make it look like regular SelectBox.
  • On document load I have added eventListener: document.getElementById("google_translate_element").addEventListener("change", onLangChange, false);
  • And finally I have added onLangChange Function to be fired up as the user changes/selects language:

    function onLangChange() {
      //option is selected
      var e = this.getElementsByTagName("select")[0];
      var txtValue = e.options[e.selectedIndex].text;
      console.log(e + " " + txtValue);
    }
    

I hope this will help someone here !!!