How can you get the bounding box of an iframe in Playwright to capture only that specific area in a screenshot?

In Playwright, when trying to capture a screenshot of an embedded iframe (like the Storybook preview iframe), using a frameLocator doesn’t directly return a bounding box, often leading to undefined values.

The expected API like frameLocator().frame().getBoundingBox() isn’t available.

The correct way is to first locate the iframe element itself (not the frame), get its bounding box via elementHandle.boundingBox(), and then use those coordinates to crop or capture a screenshot.

@saanvi.savlani I ran into this as well.

The trick is that you don’t get a bounding box from the frameLocator directly, you need to locate the actual iframe> element in the parent page first.

For example:

const iframeElement = await page.$('iframe#storybook-preview-iframe');
const box = await iframeElement.boundingBox();

await page.screenshot({
  clip: {
    x: box.x,
    y: box.y,
    width: box.width,
    height: box.height,
  },
});

This way, your screenshot captures only the iframe area.

I also got undefined when trying frameLocator().frame().boundingBox().

Always remember that boundingBox() is an ElementHandle method, so you have to target the iframe DOM element itself.

Once you have it, clipping the screenshot is straightforward.

Another tip: if your iframe is nested or dynamically resizes, you can combine elementHandle.contentFrame() with boundingBox() to ensure you capture the correct viewport coordinates:

const iframe = await page.$('iframe#my-iframe');
const frame = await iframe.contentFrame();
const box = await iframe.boundingBox();

// You can now screenshot the clipped area using box coordinates

This approach works even if the iframe scrolls or changes size dynamically.