I am currently using an iframe to load a Next.js application into my JavaScript application using its domain. However, I would like to migrate from using an iframe to rendering the Next.js application within a Shadow DOM. Unfortunately, I am facing issues rendering the Next.js application inside the Shadow DOM.
I’m trying to fetch the domain’s content and load it into the Shadow DOM, like this:
function loadNextJsContent(shadowRoot) {
return new Promise((resolve, reject) => {
// Fetch the HTML content from the Next.js app hosted at https://example.com
fetch('http://localhost:3333/page-1-uifndi')
.then(response => {
if (!response.ok) {
reject(new Error('Failed to fetch Next.js content'));
} else {
return response.text();
}
})
.then(htmlContent => {
const headContent = htmlContent.match(/<head[^>]*>([sS]*?)</head>/i)[1];
console.log('HTML Content:', htmlContent, headContent);
const template = document.createElement('template');
template.innerHTML = htmlContent;
shadowRoot.appendChild(template.content.cloneNode(true));
resolve();
})
.catch(error => {
// Handle errors and inject failure message into the Shadow DOM
console.error('Error loading Next.js content:', error);
shadowRoot.innerHTML = '<p>Failed to load content.</p>';
reject(error);
});
});
}
loadNextJsContent(shadowRoot)
.then(() => {
console.log('Next.js content loaded successfully!');
})
.catch(error => {
console.error('Failed to load content:', error);
});
I am currently able to retrieve only the HTML content, but I am unable to load the associated CSS, scripts, and fonts. Even though the content is loaded into the Shadow DOM, the styles and scripts do not appear in the network tab or take effect. What I am aiming for is functionality similar to an iframe, which automatically loads all the CSS and scripts when provided with a URL. Since Shadow DOM doesn’t support direct URL rendering, is there a way to load the complete domain content and render it within the Shadow DOM?