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
This commit is contained in:
Russell Ballestrini 2025-07-09 16:13:25 -04:00
parent f3bd60e578
commit fbe81a8298

View file

@ -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 = `
<div style="max-width: 800px; margin: 0 auto; padding: 20px; font-family: system-ui, -apple-system, sans-serif; line-height: 1.6;">
<h1 style="color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px;">
${translatedDoc.title || 'Translated Page'} (${targetLanguage.toUpperCase()})
</h1>
<div style="white-space: pre-wrap; color: #444;">
${translatedText.replace(/\n/g, '<br>')}
</div>
</div>
`;
return translatedDoc.documentElement.outerHTML;
}