Google Translate: Callback when a language is selected

10,581

Solution 1

Thanks for the responses. Based on the answers and comments in the SO questions referenced in the above responses, I cobbled together the code below which works for me.

I added a hidden div and a listener for its DOMSubtreeModified event. The listener gets called when Google translates the contents of the hidden div. However the listener gets called multiple times for each time a language is selected from the plugin drop down menu. Google seems to be making multiple passes. The original value of the innerHTML seems to be retained as a substring in all the passes except the last. So I check for the original innerHTML substring in the event handler to avoid executing the code multiple times.

Select an initial value for the innerHTML that is distinct for each language in the drop down menu. 'English' works in my case.

<html>
    <head>
    </head>

    <body>

        <!-- Google Website Translator plugin -->

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


        <div>
            <p>This part can be translated using the Google Translator plugin.</p>
        </div>

        <div id="translationDetector" style="display:none;">English</div>

        <script type="text/javascript">

            var origValue = document.getElementById("translationDetector").innerHTML;

            document.getElementById("translationDetector").addEventListener("DOMSubtreeModified", translationCallback, false);

            function translationCallback() {
                // This function needs to be called when Google translates this web page.

                var currentValue = document.getElementById("translationDetector").innerHTML;

                if (currentValue && currentValue.indexOf(origValue) < 0) {
                    origValue = currentValue;
                    alert("There is a disturbance in the force: " + currentValue);
                }
            }
        </script>
    </body>
</html>

Solution 2

Google translate js uses a cookie to keep track of the current language selection. You could set up a timeout to watch for changes to the cookie.

Here's how I implemented this for Drupal, adaptable to any javascript framework:

  Drupal.exampleLanguageChanged = function() {
if (Drupal.exampleGetCookie('googtrans') != cookieValue) {
  cookieValue = Drupal.exampleGetCookie('googtrans');
  console.log('cookie changed ' + cookieValue);
}
setTimeout(Drupal.exampleLanguageChanged, 500);
  };

  Drupal.exampleGetCookie = function(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length >= 2) {
  return parts.pop().split(";").shift();
}
return '';
  };

  Drupal.behaviors.exampleSimpleTranslation = {
attach: function(context) {
  cookieValue = Drupal.exampleGetCookie('googtrans');
  console.log('cookie value ' + cookieValue);
  setTimeout(Drupal.exampleLanguageChanged, 500);
}
  };

Share:
10,581
Codigo
Author by

Codigo

Updated on June 11, 2022

Comments

  • Codigo
    Codigo about 2 years

    I have added the Google Translate plugin to my web page. How can I get a callback to my JavaScript function whenever the user selects a language from the drop down menu that the plugin adds to my web page? The Google Translate API documentation does not seem to have any information on this. I have read through the JavaScript code of the Google Translate plugin and I cannot see anything that is helpful.

    It will also be fine if I get a callback to my function just before the translation of my web page begins or just after the translation of my web page ends or just before or after the translation of any specific element in my web page.

    Here is the HTML for a simplified version of my web page:

      <html>
        <head>
        </head>
    
        <body>
    
            <!-- Google Website Translator plugin -->
    
            <div id="google_translate_element"></div><script type="text/javascript">
            function googleTranslateElementInit() {
              new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
            }
            </script>
            <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    
    
            <div>
                <p>This part can be translated using the Google Translator plugin.</p>
            </div>
    
            <script type="text/javascript">
                function translationCallback() {
                    // This function needs to be called when Google translates this web page.
                    alert("A language was selected from the Google Translator plugin dropdown");
                }
            </script>
        </body>
    </html>
    
  • Codigo
    Codigo almost 8 years
    This may work, but I would prefer not to use it as it depends on id values like google-translate over which I do not have control.
  • FelisPhasma
    FelisPhasma almost 8 years
    @Codigo Check google's documentation, however I am pretty sure that the DOM IDs like google-translate are static
  • random_user_name
    random_user_name over 6 years
    What is find("#google-translate")? Is that intended to be a jQuery call?
  • random_user_name
    random_user_name over 6 years
    Link-only answers are not valuable. This should be a comment, as it points to an existing SO answer.
  • FelisPhasma
    FelisPhasma over 6 years
    @cale_b yes. This is code from the SO question I linked, not my code. But yes, jQuery is pretty clearly used. You can just replace the find() with $().
  • random_user_name
    random_user_name over 6 years
    My point is that find(...) is not a function. If it's jQuery, it should be something like $('#google-translate'), or $('body').find('#google-translate') - but the code you've included will not work as provided.