Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait for the iframe to finish loading, read its exposed contentDocument, and pass the target element to html2canvas. For a same-origin frame, the parent page can capture iframe.contentDocument.body (or a narrower element) because the browser permits DOM access. html2canvas also documents recursive rendering when you capture a parent element that contains a same-origin iframe.

Direct method: capture the iframe document

The browser’s same-origin policy is the prerequisite. The parent and iframe must have the same scheme, host, and port. After the frame’s navigation has completed, contentDocument refers to the active child document. If the browser does not expose that document, it returns null and html2canvas cannot render the frame from the parent.

  1. Load html2canvas on the parent page.
  2. Select the intended <iframe>.
  3. Attach the load handler before the navigation you need to capture finishes, or call the capture from application code that already knows the frame is ready.
  4. Check frame.contentDocument.
  5. Pass the frame’s body or a specific child element to html2canvas.
<iframe id="reportFrame" src="/report.html" title="Report"></iframe>
<script src="/path/to/html2canvas.min.js"></script>
<script>
  const frame = document.querySelector('#reportFrame');

  frame.addEventListener('load', async () => {
    const frameDocument = frame.contentDocument;
    if (!frameDocument) {
      throw new Error('The iframe document is not accessible from this origin');
    }

    const target = frameDocument.body;
    const canvas = await html2canvas(target);
    document.body.appendChild(canvas);
  });
</script>

The promise returned by html2canvas resolves to a canvas. Instead of appending it to the page, convert it with canvas.toBlob() or canvas.toDataURL(), display it in an image, or upload the resulting bytes.

Capture a specific element

Capturing the whole body is convenient but can include unnecessary navigation, margins, or hidden layout. Select a stable element inside the child document when you need only a panel, chart, or receipt.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
frame.addEventListener('load', async () => {
  const doc = frame.contentDocument;
  if (!doc) throw new Error('Cross-origin or otherwise inaccessible iframe');

  const panel = doc.querySelector('#invoice');
  if (!panel) throw new Error('The target element is not present');

  const canvas = await html2canvas(panel, {
    backgroundColor: '#ffffff'
  });
  document.querySelector('#preview').replaceChildren(canvas);
});

Use an application-level ready signal when the frame is a single-page application that continues rendering after its initial load event. A load event means the document navigation completed; it does not guarantee that data-driven charts or fonts have finished updating.

Capture the parent region instead

If you want the surrounding parent layout as well as the iframe, call html2canvas on a parent element. The project documentation states that same-origin iframe contents are rendered recursively.

const area = document.querySelector('#dashboard');
const canvas = await html2canvas(area);

This approach avoids selecting the child document yourself, but the output includes everything inside the parent target. Choose it for a composite dashboard; choose contentDocument when the iframe alone is the subject.

What same-origin actually means

Origin must match

Two URLs are same-origin only when their scheme, host, and port match. A frame on https://app.example.test is not same-origin with https://cdn.example.test, and a different port also creates a boundary. The browser, not html2canvas, enforces this rule.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sandbox can remove access

An iframe with a sandbox attribute can be treated as having an opaque origin. html2canvas specifically identifies a sandboxed frame without allow-same-origin as subject to the same limitation as a cross-origin frame. Do not add or remove sandbox tokens merely to make a screenshot work: sandboxing is a security control. Review the permissions your application actually needs.

Rank #2
SANDISK 128GB Ultra Flair, USB-A Flash Drive, Up to 150MB/s Read Speeds
  • High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
  • Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
  • Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
  • Sleek, durable metal casing
  • Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]

Check access before doing work

function getFrameDocument(frame) {
  const doc = frame.contentDocument;
  if (!doc) {
    throw new Error(
      'Cannot access iframe DOM. Check scheme, host, port, and sandbox settings.'
    );
  }
  return doc;
}

Cross-origin iframes: what is and is not possible

For a genuinely cross-origin frame, the parent cannot traverse the child DOM. html2canvas cannot bypass that restriction, so calling it on the parent does not turn an inaccessible frame into capturable HTML.

If you control both applications

Let the child perform its own capture and return an authorized result to the parent with a narrowly scoped postMessage protocol. The child can call html2canvas on its own DOM, then send a data URL or an application-specific completion message. Validate event.origin, use an exact targetOrigin, and avoid sending sensitive pixels to arbitrary windows.

// Child (served by the iframe's origin)
const canvas = await html2canvas(document.querySelector('#receipt'));
window.parent.postMessage(
  { type: 'receipt-image', dataUrl: canvas.toDataURL('image/png') },
  'https://app.example.test'
);

// Parent
window.addEventListener('message', event => {
  if (event.origin !== 'https://reports.example.test') return;
  if (event.data?.type !== 'receipt-image') return;
  document.querySelector('#preview').src = event.data.dataUrl;
});

postMessage is communication, not a permission escalation: it does not give the parent access to the child’s DOM.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Serve the document through an appropriate origin

If your architecture permits it, expose the content under an origin that the parent is allowed to access. This is an application and security design decision, not an html2canvas option.

Use a provider’s export route

An embedded service may offer its own export or screenshot endpoint. Use that supported facility when available; html2canvas’s image proxy settings do not provide access to a cross-origin iframe document.

Rank #3
2 Pack 64GB USB Flash Drive USB 2.0 Thumb Drives Jump Drive Fold Storage Memory Stick Swivel Design - Black
  • What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
  • Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
  • Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
  • Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
  • Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers

Iframe access and image access are separate

You can successfully read a same-origin frame and still get a broken export because the frame contains images hosted elsewhere. A canvas becomes tainted when resources are loaded without appropriate cross-origin permission, which prevents reading pixels with toDataURL or toBlob.

Enable CORS for permitted images

const canvas = await html2canvas(frame.contentDocument.body, {
  useCORS: true
});

This works only when the image server sends suitable CORS response headers and the image request meets the server’s policy. Configure the image server as well as the client option.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Proxy resource requests when appropriate

html2canvas documents a same-origin proxy as another way to load remote images. A proxy solves image-resource loading; it does not make a cross-origin iframe’s DOM readable. Treat proxying as a backend security boundary and allow only the resources your application is permitted to retrieve.

Fidelity, dimensions, and rendering options

It reconstructs the page; it does not take a browser screenshot

html2canvas builds a canvas from the DOM and the CSS properties it supports. Unsupported CSS, browser differences, web-font timing, animations, and replaced elements can therefore differ from what the user sees. Verify the styles that matter to your design rather than assuming pixel-perfect output.

Control the virtual window

windowWidth and windowHeight define the viewport dimensions used during rendering. They influence media queries and responsive layout. For a long document, use the target’s scroll dimensions when a capture is clipped.

Rank #4
SIMMAX 32GB Memory Stick USB 2.0 Flash Drives Swivel Thumb Drive Pen Drive (32GB Purple)
  • GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
  • BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
  • EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
  • TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
  • WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.
const doc = frame.contentDocument;
const target = doc.querySelector('#long-report');
const canvas = await html2canvas(target, {
  windowWidth: target.scrollWidth,
  windowHeight: target.scrollHeight
});

These values affect layout, so choose dimensions that represent the output you want, not simply the current outer iframe size.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Modify only the cloned document

The onclone callback runs after html2canvas clones the document. Hide blinking cursors, expand a collapsed section, or freeze an animation in that clone without changing the live page.

const canvas = await html2canvas(target, {
  onclone: clonedDocument => {
    clonedDocument.querySelectorAll('.no-print').forEach(el => {
      el.style.display = 'none';
    });
  }
});

Canvas size limits

Browsers impose maximum canvas dimensions and areas. Very tall or wide captures can be blank, clipped, or fail. Split a long report into sections, reduce the rendering dimensions, or capture a narrower target when the required output exceeds those limits.

Choosing an approach

Approach DOM access Control required Main trade-off
Capture the child DOM Accessible contentDocument Parent can access the frame Precise target selection; normal html2canvas CSS and resource limits still apply
Capture a parent region Same-origin recursive support Parent capture target Includes surrounding parent content
Child capture plus postMessage Parent need not inspect child DOM Code and cooperation in the child Requires a secure message protocol
Provider export or capture Provider-defined Provider must support it Behavior and output depend on that service
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting checklist

The canvas contains only the parent background

  • Confirm the iframe is same-origin, including scheme and port.
  • Check that frame.contentDocument is not null.
  • Capture the child element directly, or capture a parent target that actually contains the frame.
  • Wait for the frame’s load and application rendering to finish.

contentDocument is null

Most often the frame is cross-origin, sandboxed without allow-same-origin, or not yet navigated to the document you expect. Inspect the final frame URL and sandbox policy. If origins cannot be aligned, use child-side rendering and a validated postMessage exchange or the provider’s export API.

Output is blank or clipped

Reduce the target dimensions and set windowWidth and windowHeight to the intended scroll dimensions. Check browser canvas limits and split oversized captures.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
IMEASON Swivel Design 16GB USB Flash Drive with Keychain, USB 2.0 Portable Thumb Drive Memory Stick, FAT32 Format Flashdrive for Data Storage, Photos, Music, Files (Black, 16 GB)
  • 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
  • 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
  • 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
  • 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
  • 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.

Images disappear or pixel export throws a security error

The iframe may be accessible while its images are not. Use useCORS: true only with an image server configured for CORS, or load permitted assets through a same-origin proxy.

Styles or responsive layout differ

Set the virtual window dimensions explicitly, wait for fonts and data-driven components, and check whether the CSS property is supported by your html2canvas version. Use onclone for capture-only changes.

The frame changes while capturing

Pause animations or render a stable state in onclone. For a single-page application, trigger capture after the component reports that data, images, and fonts are ready rather than relying solely on the navigation event.

Or skip the browser setup

For server-side or repeatable captures, ScreenshotNeo returns a screenshot or PDF from one request. It removes cookie banners, newsletter popups, and chat widgets before the shot; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; and every response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server lets Claude, Cursor, and other MCP clients use take_screenshot, get_page_info, and capture_pdf.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the API when you need the rendered page rather than access to a protected iframe DOM. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 screenshots.

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(`${res.status} ${res.statusText}`);
const bytes = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));

See the ScreenshotNeo API documentation for the 63 capture options, including full-page lazy-image loading, CSS-selector element capture, device and viewport settings, custom CSS or JavaScript, request blocking, cookies and headers, caching, asynchronous jobs, bulk capture, signed links, and PDF output. Create a free ScreenshotNeo account to get 1,000 shots a month without a card.

Frequently Asked Questions

Does adding allow-same-origin always make an iframe capturable?

No. It only addresses one sandbox restriction. The frame’s effective scheme, host, and port must still be accessible to the parent, and its resources and styles must be renderable by html2canvas.

Can html2canvas capture a cross-origin iframe if I set useCORS?

No. useCORS concerns image loading. It does not grant parent-side access to a cross-origin iframe DOM.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use the iframe’s outer element or its body as the target?

Use the child document element when you need only the embedded page; use a parent target when the surrounding layout belongs in the same image.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.