Google Translate: Callback when a language is selected
Asked Answered
A

5

7

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>
Alignment answered 30/6, 2016 at 19:5 Comment(0)
A
8

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>
Alignment answered 30/6, 2016 at 23:0 Comment(0)
V
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);
}
  };
Valenti answered 22/3, 2019 at 14:52 Comment(0)
L
0

From this SO question, this code apears to work:

var $textfield = find("#google-translate");
var $popup = find("#google_translate_element");
var $select = $popup.find("select");

$textfield.click(function () {
    $popup.fadeIn("fast");
    return false;
});

$select.bind("change", function () {
    $popup.fadeOut("fast");
});
Lemonade answered 30/6, 2016 at 19:12 Comment(5)
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.Alignment
@Alignment Check google's documentation, however I am pretty sure that the DOM IDs like google-translate are staticLemonade
What is find("#google-translate")? Is that intended to be a jQuery call?Martinsen
@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 $().Lemonade
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.Martinsen
B
0

Here's one solution, but I'm not sure if I like it that much. Essentially you check to see if the text or page has changed then when it does you act on that.

Google Translate Widget - Translation complete callback

Begat answered 30/6, 2016 at 19:16 Comment(1)
Link-only answers are not valuable. This should be a comment, as it points to an existing SO answer.Martinsen
K
0

Here is jquery dependent simplifier solution :

<div id="google_translate_element"></div>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

<script>
    function googleTranslateElementInit() {
        new google.translate.TranslateElement({ pageLanguage: 'tr', includedLanguages: 'tr,en' }, 'google_translate_element');
    }
    $("body").on('change', "#google_translate_element select", function () {
        alert($(this).val())
    })
</script>
Knock answered 13/5 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.