Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Translation tool - apply pseudotranslations to text in HTML files
document.addEventListener('DOMContentLoaded', function() {
var translateButton = document.createElement('button');
translateButton.innerHTML = 'Translate';
translateButton.addEventListener('click', processPageForTranslation);
translateButton.setAttribute("style", "position: fixed; top: 0; left: 0; opacity:.5; z-index: 1000;");
translateButton.setAttribute('data-exclude-pseduotranslation', '');
document.getElementsByTagName('body')[0].appendChild(translateButton);
}, false);
function isAllWhitespace(childNode) {
return !(/[^\t\n\r ]/.test(childNode.textContent));
}
function shouldExcludeElement(element) {
return element.hasAttribute('data-exclude-pseduotranslation');
}
function processPageForTranslation() {
var elementsToTranslate = [];
var allBodyChildren = document.getElementsByTagName('body')[0].getElementsByTagName('*');
for (var c = 0; c < allBodyChildren.length; c++) {
if (!shouldExcludeElement(allBodyChildren[c])) {
elementsToTranslate.push(allBodyChildren[c]);
}
}
for (var i = 0; i < elementsToTranslate.length; i++) {
var childNode = elementsToTranslate[i].childNodes;
for (var j = 0; j < childNode.length; j++) {
if (childNode[j].nodeType === Node.TEXT_NODE) {
if (!isAllWhitespace(childNode[j])) {
translateString(childNode[j]);
break;
}
}
}
}
function translateString(itemToTranslate) {
var factor;
itemToTranslate.textContent = itemToTranslate.textContent.trim();
// The factor is used to calculate a string's expansion for pseudotranslation
if (itemToTranslate.length <= 3) {
factor = 3;
} else if (itemToTranslate.length > 3 && itemToTranslate.length <= 11) {
factor = 2;
} else {
factor = 1.5;
}
// Expanded string length which helps determine how many extra characters to prepend and append to the original string
var expansionStringLength = itemToTranslate.textContent.length * (factor - 1);
// The number of extra characters to add to the left and right of each string
var sideExpansion = Math.ceil(expansionStringLength / 2);
// You can replace 'x' with a wider character if you'd like
var halfOfExpansionString = Array(sideExpansion).join('x');
// Add space after every 8th x
halfOfExpansionString = halfOfExpansionString.replace(/(\S{8})/g, "$1 ");
itemToTranslate.textContent = '[' + halfOfExpansionString + '-' + itemToTranslate.textContent + '-' + halfOfExpansionString + ']';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.