Búsqueda de sitios web

html - Cómo inyectar Tailwind CSS en un iframe sin usar el CDN de Tailwind


Estoy trabajando con Svelte y hice un widget de chat, para el estilo usé TailwindCSS. El principal problema con los widgets de chat es que tienes que renderizarlos en un iframe para que no interfieran con el CSS de su sitio remoto. Así que logré cargarlo dentro de un iframe, pero se renderizó sin los estilos de Tailwind.

// main.ts is my file where I declared the iframe
import './app.css';
import App from './App.svelte';


// you can ignore this interface if you find it confusing

interface IWidget {
    iframeContainer: HTMLElement | null;
    init: (props: any) => void;
    createContainer: () => void;
    handleMessage: (event: MessageEvent) => void;
    setupListeners: () => void;
    
}



const app = (() => {
    // new App({
    //  target: document.getElementById('app'),
    // });
    const iframeContainer = document.createElement('div');
    iframeContainer.id = 'my-chat-widget';
    document.body.appendChild(iframeContainer);

    // create iframe
    const iframe = document.createElement('iframe');
    iframe.id = 'my-chat-iframe';
    iframe.srcdoc = `
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>My Support</title>
                <link rel="preconnect" href="https://fonts.googleapis.com" />
                <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
                <link
                    href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700&display=swap"
                    rel="stylesheet"
                />
            </head>
            <body>
                <div id="my-widget"></div>
            </body>
        </html>`;
    document.getElementById('my-chat-widget').appendChild(iframe);
    const iframeWindow: HTMLIFrameElement =
        document.getElementById('my-chat-iframe');

    document.getElementById('my-chat-iframe').onload = () => {
        new App({
            target: iframeWindow.contentWindow.document.getElementById('my-widget'),
        });
    };
})();

export default app;

el archivo de arriba es similar a index.tsx en react

Básicamente estoy apuntando directamente mi aplicación Svelte al iframe, solo que el problema que estoy enfrentando es que el CSS de Tailwind no se está cargando.

métodos que probé

  • agregando el enlace Play CDN de tailwind en head del archivo anterior. (esto funcionó pero no es factible como compilación de producción)

  • vinculando directamente el app.css en el head del archivo anterior. (esto también funcionó pero solo en modo desarrollo porque el empaquetador añade su hash de contenido, quiero que esté listo para producción)

Artículos relacionados