diff --git a/packages/clipper/src/index.ts b/packages/clipper/src/index.ts index b59654044..c01c1f382 100644 --- a/packages/clipper/src/index.ts +++ b/packages/clipper/src/index.ts @@ -23,7 +23,7 @@ import { app, h, text } from "hyperapp"; import { getInlinedNode, toBlob, toJpeg, toPng } from "./domtoimage.js"; import { Config, InlineOptions } from "./types.js"; import { FetchOptions } from "./fetch.js"; -import { downloadStylesheet } from "./styles.js"; +import { addStylesToHead } from "./styles.js"; type ReadabilityEnhanced = Readability & { PRESENTATIONAL_ATTRIBUTES: string[]; @@ -478,26 +478,7 @@ async function getPage( head.appendChild(title); if (config?.styles) { - for (const sheet of document.styleSheets) { - const node = sheet.ownerNode; - const href = - sheet.href && node instanceof HTMLLinkElement - ? node.href - : node instanceof HTMLStyleElement - ? node.getAttribute("href") - : null; - if (href) { - const styleNode = await downloadStylesheet( - href, - resolveFetchOptions(config) - ); - if (styleNode) { - head.appendChild(styleNode); - } - } else if (node instanceof HTMLStyleElement) { - head.appendChild(node.cloneNode(true)); - } - } + await addStylesToHead(head, resolveFetchOptions(config)); } return { diff --git a/packages/clipper/src/styles.ts b/packages/clipper/src/styles.ts index e6fa50980..f3c4b15fe 100644 --- a/packages/clipper/src/styles.ts +++ b/packages/clipper/src/styles.ts @@ -100,7 +100,7 @@ async function resolveImports(options?: FetchOptions) { } } -export async function downloadStylesheet(href: string, options?: FetchOptions) { +async function downloadStylesheet(href: string, options?: FetchOptions) { try { const style = document.createElement("style"); const response = await fetch(constructUrl(href, options)); @@ -428,3 +428,26 @@ function parsePseudoSelector(selector: string) { } return output; } + +export async function addStylesToHead( + head: HTMLHeadElement, + options?: FetchOptions +) { + for (const sheet of document.styleSheets) { + const node = sheet.ownerNode; + const href = + sheet.href && node instanceof HTMLLinkElement + ? node.href + : node instanceof HTMLStyleElement + ? node.getAttribute("href") + : null; + if (href) { + const styleNode = await downloadStylesheet(href, options); + if (styleNode) { + head.appendChild(styleNode); + } + } else if (node instanceof HTMLStyleElement) { + head.appendChild(node.cloneNode(true)); + } + } +}