1

I want to embed Google Translate on my HTML page; however, I want it to translate only one specific <div>. Here is an example:

<body>
    <h1>Welcome to the webpage!</h1>
    <hr/>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>In sollicitudin nulla urna, a feugiat purus volutpat eu.</p>
    <p>Phasellus ut scelerisque nisi, id elementum eros.</p>
    <p>Etiam eu lectus pharetra, rhoncus quam ultricies, semper ligula.</p>
    <p>Curabitur aliquet arcu non elementum pellentesque.</p>
    <p>Nam suscipit sit amet diam a dictum.</p>
    <br>
    <div id="parts" style="padding-top: 8px;">
        <button id="text_1">Hello</button>
        <button id="text_2">How</button>
        <button id="text_3">Are</button>
        <button id="text_4">You</button>
    </div>
</body>

So, I want only the elements inside of #parts to be translated.

Is there a way to get it done?

Thanks!

Rudy Grinberg
  • 33
  • 1
  • 9
  • Hello @rodion, can you clarify `embed google translate` part? like to have this translated when you load the page and all those under div parts translated? no previous action just when site is loaded, right? – Betjens Dec 08 '21 at 09:25
  • @Betjens I have meant "Translate this page" button embed – Rudy Grinberg Dec 08 '21 at 09:27
  • True, but there is a lot of events besides just hitting a button like load, hover, onclick (div). just trying to be specific. – Betjens Dec 08 '21 at 10:01
  • @Betjens I haven't embed the GTranslate code yet. I saw that the OG code (https://stackoverflow.com/questions/12243818/adding-google-translate-to-a-web-site) translates the whole page, so I didn't bother to add it yet. Should I? – Rudy Grinberg Dec 08 '21 at 12:12
  • Thats a way to solve it but I think you are looking just for specific tags ( in your case your div only ) – Betjens Dec 08 '21 at 12:15
  • @Betjens Yes! I need the page to remain "as-is" and translate only `
    ` child elements.
    – Rudy Grinberg Dec 08 '21 at 12:26

2 Answers2

0

In order to make use of Translate API you will have to implement a way your site can authenticate with google server and a valid project so it can make use of the API.

One of the most common ways to do this is by having your own local server which will run a google client library to authenticate and handle your translation request. Also, you can use that server to make your calls that loads the page with the already translated content.

HTML/Javascript site <--> You Local Server <--> Google Translate Service

For more information about it you can visit: OAUTH2

But lets say we don't want to go all that way and we want this small test implemented. You will still need to provide your project-id and your bearer token to actually get it working on your page.

<!DOCTYPE html>
<html>
<body onload="DoTranslation()">
    
<h1>Welcome to the webpage!</h1>
<hr/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>In sollicitudin nulla urna, a feugiat purus volutpat eu.</p>
<p>Phasellus ut scelerisque nisi, id elementum eros.</p>
<p>Etiam eu lectus pharetra, rhoncus quam ultricies, semper ligula.</p>
<p>Curabitur aliquet arcu non elementum pellentesque.</p>
<p>Nam suscipit sit amet diam a dictum.</p>
<br>
<div id="parts" style="padding-top: 8px;">
    <button id="text_1">Hello</button>
    <button id="text_2">How</button>
    <button id="text_3">Are</button>
    <button id="text_4">You</button>
</div>

<script type="text/javascript">
async function DoTranslation() { 
        const parts = document.getElementById('parts').children;
        var payload = [];
        
        for (const elems in parts)
        {
            if (parts[elems].innerText != undefined) { 
                payload.push(parts[elems].innerText);
            }
        }
    
        console.log(payload);
    
        let url = "https://translation.googleapis.com/v3/projects/<my-project-id>:translateText";
        let response = await fetch(url, {
          method: "POST",
          headers: {
            "Authorization": "Bearer <my bearer token>",  // Modified
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ 
            sourceLanguageCode: "en",
            targetLanguageCode: "es",
            contents: payload,
            mimeType: "text/plain",
          }),
        });

        let result = await response.json();
        const translations = result['translations']

        for (let i = 0; i < translations.length; i++) {
            elem_id = "text_" + (i+1); 
            document.getElementById(elem_id).innerText = translations[i]["translatedText"];
        } 
}
</script>

</body>
</html>

output

Your site will have your buttons translated.

So, how we get a project-id and a bearer token?. The project-id will have to be your google project id. go to google cloud platform site and pick the one that have your translate api enable.

Now to get a bearer token, you can use google shell editor and your service account file. See this link for details.

Set your service account .json into google_application_credentials

<my user>@cloudshell:~ (project-id)$ export GOOGLE_APPLICATION_CREDENTIALS="service-account-file.json"

Get bearer token by running below command

<my user>@cloudshell:~ (project-id)$ gcloud auth application-default print-access-token

Replace project-id and bearer token and run the sample.

To answer the question, you can perform the translate of elements but you need to careful plan what elements you want to translate to avoid sending many translate requests. You can build your stack of words and then make the call. Also, its preferably to use client libraries for it.

As a final note, you can check these links to get more information about this subject:

Betjens
  • 1,353
  • 2
  • 4
  • 13
0

When embedding Google Translate on a webpage (not the Cloud Translation API), you can use the translate and notranslate classes to specify which content should or should not be translated.

In your case, add the notranslate class to the body and the translate class to the nested element that needs translation:

<body class="notranslate">
    <h1>Welcome to the webpage!</h1>
    <hr/>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>In sollicitudin nulla urna, a feugiat purus volutpat eu.</p>
    <p>Phasellus ut scelerisque nisi, id elementum eros.</p>
    <p>Etiam eu lectus pharetra, rhoncus quam ultricies, semper ligula.</p>
    <p>Curabitur aliquet arcu non elementum pellentesque.</p>
    <p>Nam suscipit sit amet diam a dictum.</p>
    <br>
    <div id="google_translate_element"></div>
    <div id="parts" class="translate" style="padding-top: 8px;">
        <button id="text_1">Hello</button>
        <button id="text_2">How</button>
        <button id="text_3">Are</button>
        <button id="text_4">You</button>
    </div>
</body>

See the fiddle in action: https://jsfiddle.net/Rafa410/s9dg70fa/

Rafa Soler
  • 71
  • 1
  • 5