Automatic Translation Script Documentation

Overview

This script enables automatic translation of key text elements on a webpage while preserving specific protected words. It integrates Google Cloud Translation API v2 and offers dynamic language switching via a dropdown.

Features

How It Works

1. Mark Elements for Translation

const allElements = document.querySelectorAll("p, h1, h2, h3, h4, li, a, option, button");
allElements.forEach(element => {
    element.classList.add("to_translate");
});

This finds all major text-containing elements and tags them with the .to_translate class.

2. Protect Certain Words

const protectedWords = ["This Website"];

Before sending text to the API, the script replaces each protected word with a placeholder like __PLACEHOLDER_0__. After translation, placeholders are swapped back with the original words.

The reason I did this was because Google Cloud Translation API would change wording and move things around to make it grammatical, which will then appear distorted when translated back to English.

Key functions:

3. Translate Text via API

async function translate(texts, targetLang) {
  const apiKey = 'YOUR_API_KEY';
  const url = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`;
  // ...send POST request with texts, targetLang, and format: 'html'
}

The function sends an HTTP POST request to Google’s API with:

4. Replace Text in DOM

async function translate_all(language) {
  const elements = document.querySelectorAll(".to_translate");
  const originalTexts = Array.from(elements).map(el => el.innerHTML);

  const {protectedTexts, placeholders} = protectWords(originalTexts);
  const translatedTexts = await translate(protectedTexts, language);
  const restoredTexts = restore(translatedTexts, placeholders);

  elements.forEach((el, i) => el.innerHTML = restoredTexts[i]);
}

When the user selects a new language, translate_all() updates all .to_translate elements in place.

5. Dropdown Language Selection

const dropdown = document.getElementById("dropdown");
dropdown.addEventListener('change', function() {
    translate_all(this.value);
});

The <select> element’s value must match the target language code.

Requirements

Example HTML Structure

<select id="dropdown">
  <option value="en">English</option>
  <option value="fr">Français</option>
  <option value="es">Español</option>
</select>

<p>Hello World!</p>
<h1>This Website</h1>

Notes