How to Fix Html2canvas “Document Not Attached to a Window” Errors
Fix html2canvas’s “Document not attached to a Window” error by using a live DOM, an attached iframe, or page-context capture.

Direct answer: html2canvas throws Document is not attached to a Window when the element you pass belongs to a document whose defaultView is missing. This commonly happens when markup comes from new DOMParser().parseFromString(). Capture an element from the live page instead, or put trusted generated HTML into an iframe that is attached to document.body. In a browser extension, run the capture in the tab’s page context through a content script rather than capturing a detached copy created in the popup.
The guard is visible in html2canvas’s implementation: it reads element.ownerDocument, then requires ownerDocument.defaultView before calculating viewport dimensions, scroll offsets, and device-pixel ratio. If that view is absent, the function stops immediately. Viewport options such as windowWidth and windowHeight cannot bypass this earlier check. See the html2canvas source; the inspected master page reports a latest commit from August 13, 2021, so verify the behavior against the version installed in your application.
Why the error happens
A normal page element has a chain like this:

element
→ element.ownerDocument
→ ownerDocument.defaultView
→ the page's Window object
An element parsed from a string has an owner document, but that document is not necessarily attached to a browsing context. For example:
const virtualDom = new DOMParser().parseFromString(
'<main><h1>Report</h1></main>',
'text/html'
);
html2canvas(virtualDom.body); // Error: Document is not attached to a Window
The parsed document is useful for inspecting and transforming markup. It is not the same as a rendered document in a browser window. html2canvas needs the latter because it resolves computed styles, viewport size, scrolling, media-query behavior, and device pixel ratio through the window.
Choose the right fix
| Situation | Recommended approach | Reason |
|---|---|---|
| The content is already visible in the current page | Pass the live element | Its document has a real defaultView. |
| You generate trusted HTML from a string | Render it in an attached iframe, then capture the iframe body | The iframe creates an attached document and window. |
| You are capturing another tab from a browser extension | Use a content script in that tab | The script can access the page-context DOM instead of a detached popup copy. |
| You need a screenshot of a remote URL on a server | Use a browser-based screenshot service | There is no local page window to attach to in a plain Node.js process. |
Fix 1: capture an element from the live page
If the target is already rendered, do not serialize it and parse it again. Query the element directly and pass that node to html2canvas.
import html2canvas from 'html2canvas';
const target = document.querySelector('#invoice');
if (!target) {
throw new Error('Expected #invoice to exist');
}
const canvas = await html2canvas(target, {
backgroundColor: '#ffffff',
scale: window.devicePixelRatio
});
document.body.appendChild(canvas);
const pngUrl = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = pngUrl;
link.download = 'invoice.png';
link.click();
This keeps target.ownerDocument connected to the current window. If your application receives HTML from an API, render it through your normal component or template system first, wait for the browser to lay it out, and then capture the resulting element.
Wait for the layout you intend to capture
Calling html2canvas immediately after changing the DOM can capture an incomplete state. Wait for fonts, images, and asynchronous content where necessary:
await document.fonts.ready;
const images = [...document.images];
await Promise.all(images.map((image) => {
if (image.complete) return Promise.resolve();
return new Promise((resolve) => {
image.addEventListener('load', resolve, { once: true });
image.addEventListener('error', resolve, { once: true });
});
}));
const canvas = await html2canvas(document.querySelector('#report'));
An image that is cross-origin without appropriate CORS headers can still be omitted or taint the canvas. That is a separate resource-access problem; fixing the document attachment error does not grant permission to read pixels from another origin.
Fix 2: render trusted markup in an attached iframe
When the source is an HTML string, create an iframe, append it to the live page, write the trusted markup into its document, close the write, and capture the iframe body. The attachment step matters: an iframe that is never inserted into the page can leave you with the same missing browsing context.
import html2canvas from 'html2canvas';
const trustedHtml = `
<!doctype html>
<html>
<head>
<style>
body { margin: 0; font: 16px system-ui; color: #111; }
.card { width: 640px; padding: 32px; background: white; }
</style>
</head>
<body>
<section class="card">
<h1>Quarterly report</h1>
<p>Generated content rendered in an attached iframe.</p>
</section>
</body>
</html>`;
const iframe = document.createElement('iframe');
iframe.style.position = 'fixed';
iframe.style.left = '-100000px';
iframe.style.top = '0';
iframe.style.width = '720px';
iframe.style.height = '500px';
iframe.setAttribute('aria-hidden', 'true');
document.body.appendChild(iframe);
const frameDocument = iframe.contentWindow.document;
frameDocument.open();
frameDocument.write(trustedHtml);
frameDocument.close();
await new Promise((resolve) => {
iframe.addEventListener('load', resolve, { once: true });
// about:blank writes may not emit load in every browser; allow one frame.
requestAnimationFrame(resolve);
});
const canvas = await html2canvas(frameDocument.body, {
windowWidth: iframe.contentWindow.innerWidth,
windowHeight: iframe.contentWindow.innerHeight,
backgroundColor: '#ffffff'
});
document.body.appendChild(canvas);
iframe.remove();
Only write HTML your application trusts. document.write() is not an HTML sanitizer. If the string can contain user input, sanitize it with a maintained, appropriately configured sanitizer before insertion, and avoid allowing scripts or unexpected external resources.
Iframe edge cases
- Same-origin access: The example reads
iframe.contentWindow.document. A cross-origin iframe cannot be inspected this way because of the same-origin policy. - Fonts and images: Load resources inside the iframe’s document and wait for them. Parent-page styles do not automatically apply.
- Dimensions: Set explicit iframe width and height. An off-screen iframe still needs a layout viewport.
- Cleanup: Remove temporary iframes after the canvas is produced, including error paths with
try/finally. - Browser support: The workaround is community-described behavior. Validate it with your html2canvas version and supported browsers.
Fix 3: browser-extension capture
A common extension failure sequence is: the popup fetches a tab’s HTML, parses it with DOMParser, and passes the resulting body to html2canvas. That body is detached from the tab’s window. Instead, inject or register a content script and perform the query and capture in the page context.
// content-script.js
import html2canvas from 'html2canvas';
const element = document.querySelector('main');
if (!element) {
chrome.runtime.sendMessage({ ok: false, error: 'main not found' });
} else {
const canvas = await html2canvas(element);
const dataUrl = canvas.toDataURL('image/png');
chrome.runtime.sendMessage({ ok: true, dataUrl });
}
The exact manifest, host permissions, scripting permissions, and execution behavior depend on your extension manifest version and browser. Check the current browser documentation and test on pages with restrictive content-security policies. A content script also cannot freely inspect cross-origin frames inside the page.
Options that help after attachment is fixed
These options affect rendering after html2canvas passes its document guard:
| Option | Use | Important limitation |
|---|---|---|
windowWidth, windowHeight |
Set the virtual viewport used during rendering | They do not create a missing defaultView. |
scale |
Control output pixel density; device-pixel ratio is a common default | Higher values increase memory and encoding time. |
useCORS |
Attempt CORS-enabled image loading | The remote server must send suitable CORS headers. |
allowTaint |
Permit some cross-origin image behavior | A tainted canvas cannot be exported safely with toDataURL. |
backgroundColor |
Choose a solid background or null for transparency |
Transparent output can expose differences between browser and image viewers. |
ignoreElements |
Skip nodes such as animations, videos, or controls | The callback must consistently identify elements to omit. |
onclone |
Adjust the cloned document before rendering | Changes apply to the clone, not your visible page. |
Common errors and fixes
| Error or symptom | Likely cause | Fix |
|---|---|---|
Document is not attached to a Window |
Detached document from DOMParser, an orphaned iframe, or a synthetic DOM |
Use a live element or append and populate an iframe before capture. |
Cannot read properties of null |
The selector returned no element | Run after rendering, check the selector, and fail with a useful message. |
| Images are missing | Image requests failed, are cross-origin, or capture started too early | Wait for images, configure CORS, use useCORS, or serve assets from an allowed origin. |
toDataURL security exception |
The canvas is tainted by an unreadable cross-origin resource | Fix response headers and loading mode; allowTaint does not make pixels exportable. |
| Fonts differ from the page | Web fonts have not loaded in the target document | Await document.fonts.ready; load fonts inside an iframe too. |
| Blank or clipped output | Zero dimensions, overflow, animation, or capture before layout | Set dimensions, wait for layout, pause animation, and inspect scroll and overflow styles. |
| Iframe access denied | Cross-origin iframe | Capture within the iframe’s own origin or use a service that loads the URL server-side. |
Performance and reliability
Screenshot work is CPU- and memory-intensive because html2canvas walks the DOM, computes styles, paints a canvas, and often encodes a PNG. Keep the capture subtree small when possible by selecting a specific element. A very large scale, full-page layout, large shadows, SVGs, and high-resolution images multiply memory use. Release temporary canvases and iframes after exporting.

For repeatable output, freeze animations, use deterministic data, wait for fonts and images, and set an explicit viewport. Treat failed resource loads as part of the capture result instead of assuming that a resolved promise means every visual asset was present. If you need to capture many remote pages, retries, browser isolation, navigation timeouts, cookie handling, and bot checks become operational concerns that a client-side library does not solve.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF, so you do not need to create a window, attach an iframe, wait for layout, or maintain a browser worker for a URL.
See the ScreenshotNeo documentation for the complete option set. The basic calls are:
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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo supports full-page captures with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or custom viewports, retina scale, PDF paper and margin controls, custom CSS and JavaScript, click actions, selector and network-idle waits, ad and tracker blocking, custom headers, cookies, user agents and authorization, timezone and geolocation, transparent backgrounds, resizing, caching with a chosen TTL, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification.
Its capture flow accepts cookie and consent banners, then removes more than 60 known consent platforms along with newsletter popups and chat widgets; each step can be disabled. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Responses identify the result with X-Page-Verdict and X-Billed headers. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. For a URL screenshot workflow, start with the free ScreenshotNeo account.
FAQ
Can I fix the error by setting windowWidth?
No. In the inspected implementation, the missing defaultView check happens before viewport defaults and options are read. Attach the document or use a live element first.
Does DOMParser always fail with html2canvas?
A parsed document is detached in the scenario that produces this error. Rendering its markup into an attached, same-origin iframe gives it a browsing context before capture.
Can jsdom provide the missing window?
Adding a simulated DOM object does not automatically provide the browser layout, style, resource, and canvas behavior html2canvas expects. Use a real browser context for browser rendering.
Why does the iframe workaround work for trusted HTML but fail for a remote page?
The example writes same-origin markup into an iframe. A remote cross-origin document is protected by the same-origin policy, so its DOM cannot be read from the parent page.
Is this an html2canvas bug?
It is an intentional guard in the inspected source: html2canvas requires an owner document with a window. Whether a newer package changes the message or behavior must be checked against that installed version.


