From fbe81a8298f9653022470c43e9acc299780712d8 Mon Sep 17 00:00:00 2001 From: Russell Ballestrini Date: Wed, 9 Jul 2025 16:13:25 -0400 Subject: [PATCH] fix: preserve HTML structure and styling in translated pages - Update translateCurrentPage() to preserve original page HTML structure - Extract only text content for translation while keeping head/styles - Create properly formatted translated page with clean typography - Fix issue where translated pages opened in new windows lacked CSS styling --- src/translation.js | 45 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 8 deletions(-) diff --git a/src/translation.js b/src/translation.js index 07fdf71..d5dde17 100644 --- a/src/translation.js +++ b/src/translation.js @@ -353,7 +353,7 @@ export function extractPageContent() { return documentClone.documentElement.outerHTML; } -// Translate current page content +// Translate current page content while preserving HTML structure export async function translateCurrentPage(targetLanguage) { const pageContent = extractPageContent(); @@ -361,12 +361,41 @@ export async function translateCurrentPage(targetLanguage) { throw new Error("Unable to extract meaningful content from this page."); } - // Limit content length to avoid overwhelming the AI - const maxLength = 50000; // Much higher limit for complete page translation - const contentToTranslate = - pageContent.length > maxLength - ? `${pageContent.substring(0, maxLength)}...` - : pageContent; + // Create a temporary DOM to work with + const parser = new DOMParser(); + const doc = parser.parseFromString(pageContent, 'text/html'); + + // Get text content from body for translation + const bodyText = doc.body.textContent || doc.body.innerText || ''; + + if (!bodyText.trim()) { + throw new Error("No text content found to translate."); + } - return await translateText(contentToTranslate, targetLanguage); + // Limit content length to avoid overwhelming the AI + const maxLength = 50000; + const contentToTranslate = + bodyText.length > maxLength + ? `${bodyText.substring(0, maxLength)}...` + : bodyText; + + // Translate the text content + const translatedText = await translateText(contentToTranslate, targetLanguage); + + // Replace the body content with translated text while preserving structure + const translatedDoc = parser.parseFromString(pageContent, 'text/html'); + + // Create a simple structure with the translated text + translatedDoc.body.innerHTML = ` +
+

+ ${translatedDoc.title || 'Translated Page'} (${targetLanguage.toUpperCase()}) +

+
+ ${translatedText.replace(/\n/g, '
')} +
+
+ `; + + return translatedDoc.documentElement.outerHTML; }