7

I have a web page, in Dutch, with a poll with a radio button. I'd like to know which language the users speak. Is there a way I can detect if the page has been translated by Google when they submit? I do not use a translation bar, I am talking about the spontaneous google translation.

Grokify
  • 15,092
  • 6
  • 60
  • 81
Paulcraey
  • 373
  • 4
  • 14
  • 1
    This is done client side, so you cannot detect it. Inspect the accept-language header, but note that it is unreliable. – Peter Apr 10 '18 at 08:15
  • You can check the server logs to see if Google has accessed your site... – D. Pardal Apr 10 '18 at 08:16
  • I don't know if there are many people that use Google in-browser translation a lot, and hence whether that is any useful indicator for what language the user speaks. Seems like a minor roundabout scenario to worry about… – deceze Apr 10 '18 at 08:17
  • It seem browser add class to `html` tag `class="translated-ltr"` – Tan Duong Apr 10 '18 at 08:19
  • A theoretical idea: Use the onSubmit event to call a javascript function which look for a particular word. Put the result into a hidden field and then sumbit the form. On serverside create a list wich contains a range of translations for this word and compare it with submited value. – Reporter Apr 10 '18 at 08:19
  • **See Also**: [Detecting Google Chrome Translation](https://stackoverflow.com/q/4887156/1366033) – KyleMit Sep 20 '21 at 14:48

2 Answers2

5

Just check a known element if the text matches your text.

function isDutch() {
    return $('#readmore').text() === "Meer lezen";
}

or a non jQuery solution:

function isDutch() {
    document.querySelector('#readmore').innerText  === "Meer lezen";
}

Just make sure the element you have is an easy translatable sentence like read more.

Then you update a hidden field in your form with the result.

You can do this the moment a click is registered on your radio button.

I just tested it on a russian site, lenta.ru and ran $('a[href="/parts/news"]').text(); after having translated it by right clicking the page and selecting translate this page(chrome). The content returned was in my language(dutch) in the jquery text().

proof of translation detection

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
2

When translated through Google Translate, the target language is injected into the lang attribute of the main html tag, you can retrieve it with:

document.getElementsByTagName('html')[0].getAttribute('lang')

which results in something like

en-x-mtfrom-nl... and this in turn you can log to your server or set as a cookie.

Tom
  • 3,281
  • 26
  • 33
  • 5
    Actually, the lang attribute stays the same, but a class : translated-ltr is added. It shows : . If I remove the lang attribute, it shows just : . This indicates a translation, but not in which language it is translated. – Paulcraey Apr 10 '18 at 09:51