fix: convert relative CSS URLs to absolute in translated pages

- Convert relative CSS URLs to absolute URLs using current origin
- Ensure translated pages can load original blog CSS in new window
- Maintain modal functionality with external CSS files
- Skip URLs that are already absolute (http/https or protocol-relative)
This commit is contained in:
Russell Ballestrini 2025-07-09 16:23:38 -04:00
parent 761c4ec259
commit ba7885afe6

View file

@ -378,28 +378,23 @@ export async function translateCurrentPage(targetLanguage) {
// Replace the body content with translated content
doc.body.innerHTML = translatedContent;
// Inline any external CSS that might be needed for the new window
const cssLinks = doc.querySelectorAll('link[rel="stylesheet"][href*="uncloseai-modal"]');
console.log('Found CSS links to inline:', cssLinks.length);
// Convert relative CSS URLs to absolute URLs so they work in new window
const cssLinks = doc.querySelectorAll('link[rel="stylesheet"]');
const currentOrigin = window.location.origin;
for (const link of cssLinks) {
try {
console.log('Inlining CSS:', link.href);
const response = await fetch(link.href);
const cssContent = await response.text();
// Create a style element with the CSS content
const styleElement = doc.createElement('style');
styleElement.textContent = cssContent;
// Replace the link with the inline style
link.parentNode.replaceChild(styleElement, link);
console.log('Successfully inlined CSS:', link.href);
} catch (error) {
console.warn('Failed to inline CSS:', link.href, error);
// Keep the original link if fetching fails
cssLinks.forEach(link => {
const href = link.getAttribute('href');
// Skip if already absolute URL
if (href.startsWith('http') || href.startsWith('//')) {
return;
}
}
// Convert relative URL to absolute
const absoluteUrl = new URL(href, currentOrigin).href;
link.setAttribute('href', absoluteUrl);
console.log('Converted CSS URL:', href, '->', absoluteUrl);
});
return doc.documentElement.outerHTML;
}