📜 ⬆️ ⬇️

Custom googleTranslate widget for the site

Before proceeding to the writing of this article, I decided to visit the page where Google Translate Widget is generated to find out about possible changes and saw this message:
Access to the site translator is no longer possible. This will not affect those who have already installed the appropriate plugin.

We encourage users to translate web pages using browsers that have a built-in translation function.
It is not difficult to guess which browser means Google, but this is not about that. Most importantly, the plugin still remains working and we can use it. In addition, in the absence of the ability to generate a widget, this topic becomes even more relevant, because the need for machine translation has not disappeared anywhere, and Google Translate, in my opinion, is one of the most powerful tools for this.

How our example will look like:



Demo page markup
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Кастомный виджет googleTranslate для сайта</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script> <script src="js/google-translate.js"></script> <script src="//translate.google.com/translate_a/element.js?cb=TranslateInit"></script> </head> <body class="page page_fix"> <div class="language"> <img src="images/lang/lang__ru.png" alt="ru" data-google-lang="ru" class="language__img"> <img src="images/lang/lang__en.png" alt="en" data-google-lang="en" class="language__img"> <img src="images/lang/lang__de.png" alt="de" data-google-lang="de" class="language__img"> <img src="images/lang/lang__fr.png" alt="fr" data-google-lang="fr" class="language__img"> <img src="images/lang/lang__pt.png" alt="pt" data-google-lang="pt" class="language__img"> </div> <section class="content"> <h1 class="content__title">Машинный перевод сайта</h1> <div class="content__desc"> <p>Перевод сайта на другие языки при помощи Google Translate Widget</p> <p>Пример кастомоного виджета</p> <p>Hello Мир!!!</p> </div> </section> </body> </html> 


For the correct work of our custom widget, you need to connect the files:

 <link rel="stylesheet" href="css/style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script> <script src="js/google-translate.js"></script> <script src="//translate.google.com/translate_a/element.js?cb=TranslateInit"></script> 

Content style.css :

 body { margin: 0; padding: 0; } .page { display: flex; min-height: 100vh; } /* Фиксируем позицию body, которую меняет панель гугла*/ .page_fix { top: 0 !important; position: static !important; } /* Прячем панель гугла */ .skiptranslate { display: none !important; } /* language */ .language { position: fixed; left: 10px; top: 50%; transform: translateY(-50%); display: flex; flex-direction: column; } .language__img { margin: 2px; cursor: pointer; opacity: .5; } .language__img:hover, .language__img_active { opacity: 1; } /* content */ .content { text-align: center; margin: auto; } 

Used flags:



Custom widget markup:

 <div class="language"> <img src="images/lang/lang__ru.png" alt="ru" data-google-lang="ru" class="language__img"> <img src="images/lang/lang__en.png" alt="en" data-google-lang="en" class="language__img"> <img src="images/lang/lang__de.png" alt="de" data-google-lang="de" class="language__img"> <img src="images/lang/lang__fr.png" alt="fr" data-google-lang="fr" class="language__img"> <img src="images/lang/lang__pt.png" alt="pt" data-google-lang="pt" class="language__img"> </div> 

Content google-translate.js :

 const googleTranslateConfig = { lang: "ru", }; function TranslateInit() { let code = TranslateGetCode(); // Находим флаг с выбранным языком для перевода и добавляем к нему активный класс $('[data-google-lang="' + code + '"]').addClass('language__img_active'); if (code == googleTranslateConfig.lang) { // Если язык по умолчанию, совпадает с языком на который переводим // То очищаем куки TranslateClearCookie(); } // Инициализируем виджет с языком по умолчанию new google.translate.TranslateElement({ pageLanguage: googleTranslateConfig.lang, }); // Вешаем событие клик на флаги $('[data-google-lang]').click(function () { TranslateSetCookie($(this).attr("data-google-lang")) // Перезагружаем страницу window.location.reload(); }); } function TranslateGetCode() { // Если куки нет, то передаем дефолтный язык let lang = ($.cookie('googtrans') != undefined && $.cookie('googtrans') != "null") ? $.cookie('googtrans') : googleTranslateConfig.lang; return lang.substr(-2); } function TranslateClearCookie() { $.cookie('googtrans', null); $.cookie("googtrans", null, { domain: "." + document.domain, }); } function TranslateSetCookie(code) { // Записываем куки /язык_который_переводим/язык_на_который_переводим $.cookie('googtrans', "/auto/" + code); $.cookie("googtrans", "/auto/" + code, { domain: "." + document.domain, }); } 

When changing the language, cookies are added with the key googtrans and a value of the form / ru / en




This is standard behavior, so I used it to customize the widget. Clicking on the flags of the required languages, the corresponding value of the form / auto / selected_language is written into the cookie from the data-google-lang attribute. Then a reboot occurs and auto is replaced with the language written separately into the config:

 const googleTranslateConfig = { lang: "ru", }; 

This is done so that we are not tied to one language. If for example the site is translated into 2 languages, Russian and English, then we can transfer the current language to the config and correctly process it. All available languages ​​and their ISO-639-1 standard code can be found here .

The functions of adding and clearing cookies I rendered separately, so that it was possible to carry out additional checks and call in other places. The important point is that cookies need to be changed for the main domain and all subdomains.

Now, having control over our widget, we can easily implement more complex designs:



Repository with a project on github

Source: https://habr.com/ru/post/438588/