ScreenshotNeo

BlogHow-to

How to Fix htmlToImage’s CSS SecurityError When Reading cssRules in Chrome 64

Resolve html-to-image CSSOM SecurityError in Chrome 64 by checking stylesheet origins, using a local server, and configuring font embedding safely.

By the ScreenshotNeo team30 September 20268 min read

How to Fix htmlToImage’s CSS SecurityError When Reading cssRules in Chrome 64

Short answer: SecurityError: Failed to read the 'cssRules' property from 'CSSStyleSheet' usually means html-to-image tried to inspect a stylesheet that the page is not allowed to read. It is an origin-access problem, not normally invalid CSS. Identify the stylesheet, run the page from an HTTP development server instead of file://, and make controlled stylesheets same-origin or CORS-readable. If the failing access is only needed for font discovery, use the installed html-to-image version’s fontEmbedCSS or skipFonts options.

Chrome 64 made this failure visible in cases that had appeared to work before. The correct fix depends on the stylesheet URL, how the page was loaded, and the html-to-image version.

1. What the error means

Browsers protect the CSS Object Model (CSSOM). JavaScript can read document.styleSheets, but reading sheet.cssRules may throw when the sheet comes from another origin or was loaded in a way that does not grant CSSOM access.

html-to-image inspects stylesheets and embeds fonts before rendering the final image.
html-to-image inspects stylesheets and embeds fonts before rendering the final image.
SecurityError: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules

html-to-image clones the target node, copies computed styles, discovers and embeds web fonts, then renders the serialized result. Font discovery can inspect every stylesheet in the document, including a font provider, an embedded widget, an analytics tool, or an extension-injected sheet. Therefore a sheet unrelated to the element you selected can still cause the conversion to fail.

2. Diagnose the exact stylesheet first

  1. Read the complete console error and stack trace.
  2. Record the stylesheet URL if one is shown. A null owner or missing URL can indicate an inline, injected, or browser-created sheet.
  3. Check the sheet’s origin against the page origin, including protocol, hostname, and port.
  4. Note whether the page was opened as file://, from a local HTTP server, or from a deployed HTTPS origin.
  5. Record the installed html-to-image version and inspect its bundled types or README before using an option.

Typical causes include:

Cause Why it fails First action
Page opened with file:// Local-file origin rules can prevent readable CSSOM rules. Serve the project through its development server.
Third-party stylesheet The requesting page is not permitted to inspect its rules. Check the stylesheet response and loading mode; use a same-origin copy or appropriate CORS.
Google Fonts or another font provider html-to-image may inspect it while embedding fonts. Supply explicit font CSS or deliberately skip font embedding.
Widget, extension, or injected CSS The sheet can be encountered even when the target does not use it. Disable the injector for diagnosis and confirm the failing URL.

3. Run the page through a local development server

If you double-clicked an HTML file, stop testing that way first. Start the project’s normal development server, then open its HTTP or HTTPS URL. For a static directory, one example is:

python3 -m http.server 8000 --directory .

Open http://localhost:8000/ and retry the conversion. This gives the document a real HTTP origin and avoids the local-file behavior that commonly exposes the Chrome 64 CSSOM restriction.

Do not treat disabling browser web security as a normal fix. It weakens the browser’s protections and does not correct the headers or origin behavior that real users will receive.

4. Restore access for stylesheets you control

Keep application CSS same-origin

When practical, serve the stylesheet from the same origin as the application. Check the final URL in DevTools rather than relying on the source code URL; redirects, a CDN hostname, or a different port can change the origin.

Configure CORS on the stylesheet response

If the stylesheet must be hosted elsewhere, configure that stylesheet host to grant the application origin access. The relevant response is the CSS response itself. Adding Access-Control-Allow-Origin to an unrelated API, image, or font endpoint does not make cssRules readable.

Verify:

  • The stylesheet request URL and response status.
  • The response’s Access-Control-Allow-Origin value.
  • Whether credentials are involved; wildcard access is incompatible with credentialed requests.
  • The stylesheet’s request mode and any redirects.

After changing headers, reload without a stale service-worker or CDN response and inspect the actual network response again.

5. Complete html-to-image example with diagnostics

The following browser example reports stylesheets that throw when their rules are read, then converts a target element. It is useful for diagnosis; it does not bypass browser security.

import { toPng } from 'html-to-image';

const target = document.querySelector('#invoice');

for (const [index, sheet] of [...document.styleSheets].entries()) {
  try {
    // Access can throw even when the sheet object exists.
    void sheet.cssRules;
  } catch (error) {
    console.warn('Unreadable stylesheet', {
      index,
      href: sheet.href,
      error
    });
  }
}

try {
  const dataUrl = await toPng(target, {
    cacheBust: true
  });
  const link = document.createElement('a');
  link.download = 'invoice.png';
  link.href = dataUrl;
  link.click();
} catch (error) {
  console.error('html-to-image conversion failed', error);
}

The try/catch around cssRules is diagnostic. It does not grant access to a cross-origin sheet. The server and loading configuration must permit access.

6. When font discovery is the failing operation

html-to-image’s font embedding path searches stylesheet rules for @font-face, fetches font files, and embeds them in the generated image. If the blocked sheet is only needed for that discovery step, choose between preserving the font and bypassing discovery.

Option A: provide fontEmbedCSS

Current html-to-image documentation describes fontEmbedCSS as supplied CSS for embedding fonts. This replaces automatic stylesheet discovery. Verify that your installed package exposes the option before shipping it.

import { toPng, getFontEmbedCSS } from 'html-to-image';

const node = document.querySelector('#invoice');

// Run this only when the stylesheets needed for discovery are readable.
const fontEmbedCSS = await getFontEmbedCSS(node);

const image = await toPng(node, {
  fontEmbedCSS
});

document.querySelector('#preview').src = image;

For production, store or generate the exact font CSS your application needs and pass it directly. Confirm that the referenced font files are reachable and that the resulting image uses the expected typeface.

Option B: use skipFonts

Current types also document skipFonts. It bypasses font download and embedding:

import { toPng } from 'html-to-image';

const image = await toPng(document.querySelector('#invoice'), {
  skipFonts: true
});

This can remove the CSSOM failure, but text may fall back to a different font, changing glyph widths, line wrapping, and layout. Compare the output before adopting it.

Choice Preserves custom fonts? Effect
Fix same-origin/CORS access Yes Restores normal stylesheet and font discovery.
fontEmbedCSS Usually, if the supplied CSS is complete Skips automatic discovery and uses your CSS.
skipFonts No Skips font embedding; fallback metrics may change.

7. A controlled compatibility patch

Some historical discussions suggested checking whether a stylesheet had a cssRules property before reading it. That guard is not a universal cross-origin fix: an existing property can still throw when its getter is accessed.

If you must patch a pinned dependency, catch the access error and skip that sheet deliberately:

function readableRules(sheet) {
  try {
    return sheet.cssRules;
  } catch (error) {
    console.warn('Skipping unreadable stylesheet', sheet.href, error);
    return null;
  }
}

for (const sheet of document.styleSheets) {
  const rules = readableRules(sheet);
  if (!rules) continue;
  // Process rules only when access succeeded.
}

Review this as a version-specific compatibility change. Skipping a sheet can omit required fonts or styles, and an upstream update may change the code you patched.

8. Troubleshooting checklist

Symptom Likely cause Fix
Fails only when opened by double-click file:// origin Use the project’s local HTTP development server.
Fails after adding a CDN stylesheet Cross-origin CSSOM access Serve it same-origin or configure CORS on that CSS response.
Stack mentions font embedding Unreadable font stylesheet Use accessible CSS, fontEmbedCSS, or accept the typography change from skipFonts.
Only one browser profile fails Extension-injected stylesheet Repeat with extensions disabled and identify injected CSS.
CORS header appears present but error remains Header is on the wrong response, redirect, or request mode is incompatible Inspect the final CSS response and request details in DevTools.
Image renders with wrong text metrics Fonts were skipped or incompletely embedded Restore font access or provide complete embed CSS.
Option is reported as unknown Installed html-to-image version predates the option Check the package’s installed types and documentation before upgrading or changing code.

9. Performance and reliability considerations

  • Font discovery adds stylesheet inspection and font downloads. Reusing verified embed CSS can reduce repeated discovery work.
  • Skipping fonts may be faster, but visual differences can invalidate pixel comparisons and documents.
  • Keep conversion inputs deterministic: use a stable HTTP origin, wait for fonts and images, and avoid extension-injected resources.
  • Test with the same protocol, host, port, redirects, and authentication model used in deployment.
  • Log the failing stylesheet URL, package version, browser version, and selected font options so regressions can be diagnosed.

10. Or skip the browser setup

If your goal is a clean website image rather than running html-to-image inside your page, ScreenshotNeo provides a server-side screenshot API. It avoids browser CSSOM setup and accepts one GET request.

A server-side capture can clean common overlays before returning the screenshot.
A server-side capture can clean common overlays before returning the screenshot.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo documentation for request options. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers report the page verdict and billing result. ScreenshotNeo also includes an MCP server for AI agents with take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots per month without a card, and paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account.

11. FAQ

Do I need to put all CSS on my own server?

No. You need readable CSSOM access for stylesheets html-to-image inspects. Same-origin hosting is often simplest; controlled CORS on the stylesheet response is another option.

Is this a CSS syntax error?

Usually no. The message indicates that the browser rejected access to stylesheet rules. Validate CSS separately, but start with origin and loading checks.

Will adding CORS to my font file fix it?

Not necessarily. The failing operation may be reading the stylesheet’s cssRules. Inspect the CSS response and its access policy first.

Should I always set skipFonts?

No. Use it only when fallback typography is acceptable. It can change text metrics and layout.

Can a stylesheet unrelated to my element cause the error?

Yes. Font discovery can inspect document stylesheets beyond the target node’s directly visible styles.

Why does a guard around cssRules still fail?

Because the property can exist while its getter throws. Catch the access error or fix the stylesheet’s origin and loading permissions.