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.
.to_translate class to <p>, <h1>–<h4>, <li>, <a>, <option>, and <button> elements."This Website" during 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.
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:
protectWords(texts) – replaces protected words with placeholders.restore(translatedText, placeholders) – restores protected words after translation.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:
q: array of text stringstarget: language code (e.g., "fr", "es")format: "html" to preserve HTML structureasync 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.
const dropdown = document.getElementById("dropdown");
dropdown.addEventListener('change', function() {
translate_all(this.value);
});
The <select> element’s value must match the target language code.
apiKey)<select> element with id="dropdown" in the HTML"fr", "es", "de") as <option> values<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>