Skip to content

Instantly share code, notes, and snippets.

@JohnRSim
Last active July 11, 2024 09:18
Show Gist options
  • Save JohnRSim/f973e97764988bffd27cd991c97b7bdd to your computer and use it in GitHub Desktop.
Save JohnRSim/f973e97764988bffd27cd991c97b7bdd to your computer and use it in GitHub Desktop.
Crawl & replace generated text with static translation
// Function to collect all text nodes
function getTextNodes(element) {
let textNodes = [];
function recursiveCollect(node) {
if (node.nodeType === Node.TEXT_NODE) {
// Check if the node value is not blank or just newline characters
if (node.nodeValue.trim() !== "") {
textNodes.push(node);
}
} else {
node.childNodes.forEach(recursiveCollect);
}
}
recursiveCollect(element);
return textNodes;
}
// Example JSON object with translated text
const translations = {
"Hello, world!": "Hola, mundo!",
"This is a test.": "Esto es una prueba.",
// Add more translations as needed
};
// Function to replace text nodes with translated text
function replaceTextNodes(textNodes, translations) {
textNodes.forEach(node => {
const originalText = node.nodeValue.trim();
if (translations[originalText]) {
node.nodeValue = translations[originalText];
}
});
}
// Collect all text nodes in the body
const textNodes = getTextNodes(document.body);
// Replace the text nodes with translated text from the JSON object
replaceTextNodes(textNodes, translations);
console.log("Text replacement complete.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment