get selected language form google translator

1.9k Views Asked by At

I am using google translator to translate my website into multiple languages. But for some reason I want to get the selected language to trigger some function. I have gone through some questions based on this in stack overflow but those does not help me, for example this and this.

Here is my javascript code which I am using to translate.

function googleTranslateElementInit() {
              new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es,hi,th,vi,zh-CN', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
            }

Your suggestion will help me a lot.

1

There are 1 best solutions below

1
On

The currently selected language is stored in a cookie named googtrans.

Here's a simple example of grabbing the value from the cookie (based on cookie code from here: What is the shortest function for reading a cookie by name in JavaScript?):

function readCookie(name) {
    var c = document.cookie.split('; '),
    cookies = {}, i, C;

    for (i = c.length - 1; i >= 0; i--) {
        C = c[i].split('=');
        cookies[C[0]] = C[1];
     }

     return cookies[name];
}
console.log(readCookie('googtrans')); //eg. 'en/no' for Norwegian, '/en/hr' for Croatian, etc.

Updated

I have checked many functions to get selected language name on change of language but not working for me, so here is something I have tried.

You can set time out function and get the name of last selected language every time

$(document).ready(function(){
    checkChange();
});
var currentLang = "";
function checkChange()
{
    setTimeout(function(){
        readCookie('googtrans');
    },2000);
}

function readCookie(name) {
    var c = document.cookie.split('; '),
    cookies = {}, i, C;

    for (i = c.length - 1; i >= 0; i--) {
        C = c[i].split('=');
        cookies[C[0]] = C[1];
     }

     currentLang = cookies[name];
     console.log(currentLang);
     checkChange();
}

Hope this will help you.