Q
Q
Quber2014-04-02 09:06:42
Google
Quber, 2014-04-02 09:06:42

What is the script for translating a page from Russian into English?

Previously, there was a jquery plugin for a site that could translate a page on the fly into any language with a single keystroke. I need to implement multilingualism on the site, and such a plugin would come in handy, bearing in mind its ease of connection and minimal labor costs for its (multilingualism) implementation.

As far as I know, Google Translate API has become paid. Support and operation of such a plugin has stopped. There is a kind of analogue of the Bing Translate API. But I need the js script itself. Are there any in nature? Translation should be carried out without going to third-party sites.

Thank you.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Azerlund6214, 2020-09-01
@Azerlund6214

Making this answer for future generations.
Literally just successfully connected GTApi to the site, I post what and how.
At the time of 010920 GTApi officially ceased to distribute, however, they left the opportunity for already working sites to use it.

Text from their website

https://translate.google.com/intl/en/about/website/
Мы больше не предоставляем новый доступ к Переводчику веб-сайтов Google Translate. Это изменение не влияет на существующее использование Переводчика веб-сайтов.
Мы рекомендуем пользователям, которые хотят переводить веб-страницы, использовать браузеры, которые изначально поддерживают перевод.
====
We no longer provide new access to Google Translate's Website Translator. This change does not affect existing use of the Website Translator.
We encourage users looking to translate webpages to use browsers that support translation natively.

Expected result from the guide below:
  • A simple list with flags + language names. (Customize yourself)
  • When clicked, the entire page is translated into the desired language. No reboots or anything.
  • The selected language is stored in cookies, so all other pages will be automatically translated as well.
  • You can make it possible to select a language, for example, only on the landing page and not on other pages.

Connection:
1) Copy-paste this code into a separate .js file:
JS code for copy-paste
(function() {
    var d = "text/javascript"
      , e = "text/css"
      , f = "stylesheet"
      , g = "script"
      , h = "link"
      , k = "head"
      , l = "complete"
      , m = "UTF-8"
      , n = ".";

    function p(b) {
        var a = document.getElementsByTagName(k)[0];
        a || (a = document.body.parentNode.appendChild(document.createElement(k)));
        a.appendChild(b)
    }


    
    function _loadJs(b) {
        var a = document.createElement(g);
        a.type = d;
        a.charset = m;
        a.src = b;
        p(a)
    }


    function _loadCss(b) {
        var a = document.createElement(h);
        a.type = e;
        a.rel = f;
        a.charset = m;
        a.href = b;
        p(a)
    }

    function _isNS(b) {
        b = b.split(n);
        for (var a = window, c = 0; c < b.length; ++c)
            if (!(a = a[b[c]]))
                return !1;
        return !0
    }

    function _setupNS(b) {
        b = b.split(n);
        for (var a = window, c = 0; c < b.length; ++c)
            a.hasOwnProperty ? a.hasOwnProperty(b[c]) ? a = a[b[c]] : a = a[b[c]] = {} : a = a[b[c]] || (a[b[c]] = {});
        return a
    }

    window.addEventListener && "undefined" == typeof document.readyState && window.addEventListener("DOMContentLoaded", function() {
        document.readyState = l
    }, !1);

    if (_isNS('google.translate.Element')) {
        return
    }



    (function() {
        var c = _setupNS('google.translate._const');
        c._cl = 'ru';
        c._cuc = 'googleTranslateElementInit';
        c._cac = '';
        c._cam = '';
        c._ctkk = eval('((function(){var a\x3d71640675;var b\x3d-12312877;return 406476+\x27.\x27+(a+b)})())');
        var h = 'translate.googleapis.com';
        var s = (true ? 'https' : window.location.protocol == 'https:' ? 'https' : 'http') + '://';
        var b = s + h;
        c._pah = h;
        c._pas = s;
        c._pbi = b + '/translate_static/img/te_bk.gif';
        c._pci = b + '/translate_static/img/te_ctrl3.gif';
        c._pli = b + '/translate_static/img/loading.gif';
        c._plla = h + '/translate_a/l';
        c._pmi = b + '/translate_static/img/mini_google.png';
        c._ps = b + '/translate_static/css/translateelement.css';
        c._puh = 'translate.google.com';
        _loadCss(c._ps);
        _loadJs(b + '/translate_static/js/element/main_ru.js');
    })();
})();





  var cookie = get_cookie( 'googtrans' );
  if (cookie == null) {
    $('.translate .lang_ru').addClass('active')
  }else{
    var get_cook = cookie.split('/')[2];
    $('.translate .lang_'+get_cook).addClass('active');
  }

  function doGTranslate(lang_pair) {

    $('.translate li').click(function () {
      $('.translate li').removeClass('active');
      $(this).addClass('active');
      return false;
    });

    if (lang_pair.value)
      lang_pair = lang_pair.value;
  //	if (lang_pair == '')
  //		return;

    var lang = lang_pair.split('|')[1];
    var teCombo;
    var sel = document.getElementsByTagName('select');
    for (var i = 0; i < sel.length; i++)
      if (sel[i].className == 'goog-te-combo')
        teCombo = sel[i];

    if (document.getElementById('google_translate_element') == null  || document.getElementById('google_translate_element').innerHTML.length == 0 || teCombo.length == 0 || teCombo.innerHTML.length == 0) {
      setTimeout(function() {
        doGTranslate(lang_pair)
      }
      , 500);

    }
    else {
      teCombo.value = lang;
      GTranslateFireEvent(teCombo, 'change')
    }
  };

  function GTranslateFireEvent(element, event) {
    try {
      if (document.createEventObject) {
        var evt = document.createEventObject();
        element.fireEvent('on' + event, evt)
      }
      else {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(event, true, true);
        element.dispatchEvent(evt)
      }
    }
    catch (e) {}
  };



function get_cookie ( cookie_name ) {
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

  function googleTranslateElementInit() {
    new google.translate.TranslateElement({
      pageLanguage: 'ru'
    },'google_translate_element');
  };


2) Connect this in the header on each page :
<script src=".../Код_выше.js"></script>
<style type="text/css">
    body { top: 0px !important; } /* Убираем отступ который выставляет скрипт */
    .skiptranslate { display: none !important; } /* Скрываем гугловский навбар с выбором языка  */
</style>

We insert this at the very top of the body. Necessarily necessary for the translator, without this element nothing will work.
Connect on every page. 3) We make the simplest design.
<div id="google_translate_element"></div>
<ul class="translate">

     <li class="">
              <a href="#" onclick="doGTranslate('ru|en');"> <!-- Переводим сайт с русского на английский -->
              <img height="20" width="30"
                    alt="Флаг страны 1"
                   src="Папка с флагами\флаг1.png">
              <span>
                    Язык 1
              </span>
          </a>
      </li>

</ul>

Ready-made code for the blade template engine, with the output of all flags in a loop
<div id="languages-boxes">

            @php
            $langFrom = 'en'; # С какого языка переводим. (Исходный язык сайта)
            $langFlagsImgFolder = 'public\\Flags'; # Путь к папке с флагами.

            $langsSettings = array(
                [ 'GTLangName'      => 'en',   # Имя языка в GoogleTranslate
                  'img-alt'         => 'Eng',  # Alt для флага
                  'image-flag-name' => 'gb',   # Имя файла с флагом.  ...\000.png
                  'text'            => 'English', ],  # Подпись рядом с флагом

                [ 'GTLangName'        => 'fr',
                    'img-alt'         => 'Franc',
                    'image-flag-name' => 'fr',
                    'text'            => 'French', ],

                [ 'GTLangName'        => 'de',
                    'img-alt'         => 'Germ',
                    'image-flag-name' => 'de',
                    'text'            => 'German', ],

                [ 'GTLangName'        => 'it',
                    'img-alt'         => 'Ital',
                    'image-flag-name' => 'it',
                    'text'            => 'Italian', ],

                [ 'GTLangName'        => 'ru',
                    'img-alt'         => 'Rus',
                    'image-flag-name' => 'ru',
                    'text'            => 'Russian.', ],
            );
            @endphp

            {{-- Тут любой внешний вид верстки --}}
            <ul class="translate">

                @foreach( $langsSettings as $oneLang )

                <li>
                    <a href="#" onclick="doGTranslate('{{$langFrom}}|{{$oneLang['GTLangName']}}');">

                        <img height="20" width="30"
                             alt="{{$oneLang['img-alt']}}"
                             src="{{$langFlagsImgFolder}}\{{$oneLang['image-flag-name']}}.png">

                        <span>
                           {{$oneLang['text']}}
                        </span>

                    </a>
                </li>
                @endforeach

            </ul>


        </div>

You can download all the flags in one archive here
Result:
5f4e475def963194533869.jpeg
Cons and important pitfalls:
  • Immediately after connecting js in the header, 3 more files will automatically be connected under it.
  • + 2 divs will be connected at the top of the body.
  • + 2 divs + 2 iframes will be connected at the bottom of the body.
  • All translatable texts will be wrapped in a double font tag.
  • We hid the Google Navbar, but in fact it hasn't gone anywhere - We don't see it, but it's there.
  • Most importantly, the styles of the html and body tags are rewritten. That is, in the entry, Styles will be completely replaced by what the script inserts.<body style="ваш стиль">

ฅ^•ﻌ•^ฅ

A
Alexander Zachinalov, 2014-04-02
@SanDiesel

I haven’t heard about GTApi being paid, at least they don’t have any applications for this:
translate.google.com/manager/website/add?hl=en
you do the setup, you get the code, nothing complicated...

G
GreatRash, 2014-04-02
@GreatRash

api.yandex.ru/translate - will it work?

J
jane jane, 2014-04-03
@ru_janex

google translate allows you to do this
sustec.ru (look in the footer)

A
Alexey Skleinov, 2018-09-06
@lexskal

minskstay.by my implementation is in the basement while it works. we do not determine the language affiliation, by default the choice of language was during authorization, but it was refused, although it was not required at all. Therefore, only the translator remained in the basement.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question