Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
Serialize programmatic CSS style sheets (stylesheets that use CSSOM API)?

You can use document.documentElement.outerHTML in order to serialize a document to a HTML string.

However, if we paste the result into a file and try to render it as HTML, it will not be always be faithful to the original display (ignoring truly dynamic elements like canvas). Why? Any website that uses CSS in JS will have empty style tags that effect the styling of the web-page. These stylesheets are manipulated using the CSSOM API.

I want to serialize web-pages while also including stylesheets that are programatically manipulated. What would be the best way to do this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

My solution:

export function getCSSOMStyles(): string {
  const { styleSheets } = document;
  const CSSOMSheets = Array.from(styleSheets).filter((sheet) => {
    const hasHref = Boolean(sheet.href);
    //@ts-expect-error - too hard to Typescriptify
    const hasStylesInDOM = (sheet.ownerNode?.innerText?.length || 0) > 0;
    return sheet.cssRules && !hasHref! && !hasStylesInDOM;
  });

  const CSSOMStylesText = CSSOMSheets.map((sheet) =>
    Array.from(sheet.cssRules)
      .map((rule) => rule.cssText)
      .join("")
  ).join("");
  return CSSOMStylesText;
}

export const injectCSSOMStyles = (document: Document) => {
  const styles = getCSSOMStyles();
  if (styles.length === 0) return;

  const styleSheet = document.createElement("style");
  // TODO: Why is this deprecated?
  styleSheet.type = "text/css";
  const stylesText = document.createTextNode(getCSSOMStyles());
  styleSheet.appendChild(stylesText);
  document.head.appendChild(styleSheet);
};

export const serializeCSSInJSStyles = injectCSSOMStyles;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda