Google Translate

How To Google Translate Button on Website

Google Translate is a free multilingual machine translation service. It can translate the Website’s text content from one language to another. It offers a huge list of languages to translate and has an efficient, reliable and easy way to translate the webpage in whatever language the user wants. It supports over 100 languages. Use this website translator to convert webpages into your choice of language.

So, How to add Google Translate Button on a website?

To directly translate your documents, you can go to https://translate.google.com/ . But to add it on your website, you need to add Google Translate Script on the webpage

To use google translate script, you need to import google api containing googleTranslateElementInit() function with new google.translate.TranslateElement() and google_translate_element id .

We will use a CDN path, provided by Google, to implement the google translator. Just follow the whole tutorial to earn how to add google translate ( translate google com ). You can download complete html code of examples from Try-it Editor .

Google Translate Button

We will implement it in a simple web page, but you can make a beautiful design and then place the translator button properly.

Google Translate implementation will need three steps:

  • Set up CDN Path for Google API.
  • Set up a div element to place Translator.
  • Set up Default Language for the Webpage.

Let’s implement all the steps:

Step 1: Set the CDN path to Google Translate API. This CDN will only work if you have an active internet connection otherwise not. This path will add the script of Translator on your page.

Step 2: Add a element with id=google_translate_element . It is a predefined id in google’s script. This div element will be used by the Translator API to give the user a list of languages.

Your Website Heading

Step 3: Add Script to choose default language of the webpage. Every language has a unique code in Translator; you can check the list from here. We have selected American English as default, and the code is ‘en’ .

Now, add all these together. You are ready to use the Translator. Go to the Try-it editor to see the results. You can also download the full code from the Editor. Click on Try This Code.

Читайте также:  Наследуются ли приватные поля java

Your Web Page

Click on the dropdown button to translate.

Translate this page:

You can translate the content of this page by selecting a language in the select box.

Output

Your Web Page

Click on the dropdown button to translate.

You can translate the content of this page by selecting a language in the select box.

Источник

Кастомный виджет googleTranslate для сайта

Получить доступ к переводчику сайтов больше нельзя. Это никак не отразится на тех, кто уже установил соответствующий плагин.

Советуем пользователям переводить веб-страницы с помощью браузеров, имеющих встроенную функцию перевода.

Не сложно догадаться какой браузер имеет ввиду Google, но речь не об этом. Самое главное, что плагин все также остается рабочим и мы можем им пользоваться. Кроме того, за неимением возможности генерировать виджет, данная тема становиться еще более актуальной, ведь потребность в машинном переводе никуда не исчезла, а Google Translate, на мой взгляд, один из самых мощных инструментов для этого.

Как будет выглядеть наш пример:

            
ru en de fr pt

Машинный перевод сайта

Перевод сайта на другие языки при помощи Google Translate Widget

Пример кастомоного виджета

Hello Мир.

Для корректной работы нашего кастомного виджета необходимо подключить файлы:

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

Разметка кастомного виджета:

 
ru en de fr pt

Содержимое 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, >); > 

При смене языка добавляется куки с ключом googtrans и значением вида /ru/en

  • /ru — это язык который переводим
  • /en — это язык на который переводим

Это стандартное поведение, поэтому я им и воспользовался для кастомизации виджета. Кликая по флажкам необходимых языков, из атрибута data-google-lang в куки записываются соответствующие значение вида /auto/выбранный_язык. Затем происходит перезагрузка и auto заменяется на язык записанный отдельно в конфиг:

const googleTranslateConfig = < lang: "ru", >;

Это сделано для того, чтобы мы не привязывались к одному языку. Если к примеру сайт переведен на 2 языка, русский и английски, то мы можем передать текущий язык в конфиг и правильно обработать его. Все доступные языки и их код стандарта ISO-639-1 можно найти тут.

Функции добавления и очисти куки я вынес отдельно, чтобы была возможность провести дополнительные проверки и вызвать в других местах. Важный момент, куки необходимо менять для основного домена и всех поддоменов.

Теперь, имея контроль над нашим виджетом, мы можем без проблем реализовывать более сложные дизайны:

Источник

How to add google translate button on a Website/Blogger using javascript

You must add Google Translate button in your website so that the viewers can easily read your article using their own language.

Benefit : It will increase the number of viewers and also revenues.

How to add google translate button on Your Website

There are only three steps to implement a custom google translate button on your website.

    At first you need to add a element with the id «google_translate_element» such as [id=»google_translate_element»] . Example

html> head>title>Google Translate Button/title> /head> body> h2>This is a simple web page./h2> div id="google_translate_element">/div> /body> /html>
script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">/script>
script type="text/javascript"> function googleTranslateElementInit() new google.translate.TranslateElement(pageLanguage: 'en'>, 'google_translate_element'); > /script>

here ‘en’ is your webpage Language. You can change it if your webpage language is different. Like :- Hindi = hi, Bengali = bn , German = de

Finally, Google translate button is ready to translate the content of your page.

html> head> title>Google Translate Button/title> /head> body> h2>This is a simple web page./h2> p>This is a simple web page and you can translate the content of this page by selecting your language in the select box/p> div id="google_translate_element">/div> script type="text/javascript"> function googleTranslateElementInit() new google.translate.TranslateElement(pageLanguage: 'en'>, 'google_translate_element'); > /script> script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">/script> /body> /html>

Button Modes

There are currently three type of buttons for the Google Translate button.

Horizontally

!DOCTYPE html> html> head> title>Google Translate Button/title> /head> body> h2>This is a simple web page./h2> p> This is a simple web page and you can translate the content of this page by selecting your language in the select box /p> div id='google_translate_element'>/div> script> function googleTranslateElementInit() new google.translate.TranslateElement( pageLanguage: 'en', autoDisplay: 'true', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL >, 'google_translate_element'); > /script> script src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'>/script> p> This example displays a HORIZONTAL translate button. /p> /body> /html>
!DOCTYPE html> html> head> title>Google Translate Button/title> /head> body> h2>This is a simple web page./h2> p>This is a simple web page and you can translate the content of this page by selecting your language in the select box/p> div id='google_translate_element'>/div> script> function googleTranslateElementInit() new google.translate.TranslateElement( pageLanguage: 'en', autoDisplay: 'true', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL >, 'google_translate_element'); > /script> script src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'>/script> p>This example displays a VERTICAL translate button./p> /body> /html>
!DOCTYPE html> html> head> title>Google Translate Button/title> /head> body> h2>This is a simple web page./h2> p>This is a simple web page and you can translate the content of this page by selecting your language in the select box/p> div id='google_translate_element'>/div> script> function googleTranslateElementInit() new google.translate.TranslateElement( pageLanguage: 'en', autoDisplay: 'true', layout: google.translate.TranslateElement.InlineLayout.SIMPLE >, 'google_translate_element'); > /script> script src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'>/script> p>This example displays a VERTICAL translate button./p> /body> /html>

how to google translate a website,how to add google translate button on a Website/Blogger,translate google,how to use google translate,how to translate a web page,how to google translate a page,how to translate a website to english,how to translate google page,how to google translate a website,how to translate language in google

Источник

How TO — Google Translate

Learn how to add a Google Translate button on your web page.

Example

Google Translate Button

Start with a simple basic web page.

Add a element with the id «google_translate_element»:

Example

My Web Page

Add a reference to the translate API at google.com:

Example

Add a javascript function:

Example

And you are ready to translate the content of your page:

Example

My Web Page

function googleTranslateElementInit() new google.translate.TranslateElement(, ‘google_translate_element’);
>

Button Modes

There are currently three different design modes for the Google Translate button.

Example

Example

Example

A dropdown menu, with no other text:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью