Skip to content
jshacks.dev
Browser

Embed an iframe and resize it to its content

Size an iframe to its content by sending the document height with postMessage from the frame and a message listener in the parent page.

1 min read
Summarize in AI

A same-origin iframe can be measured directly, but a cross-origin one cannot. The frame has to report its own height, and the parent applies it.

frame.jsJavaScript
// runs inside https://widgets.example.test/card
const send = () => {
  const height = document.documentElement.scrollHeight;
  parent.postMessage({ type: 'resize', height }, 'https://app.example.test');
};

new ResizeObserver(send).observe(document.documentElement);
parent.jsJavaScript
const frame = document.querySelector('iframe');

window.addEventListener('message', (event) => {
  if (event.origin !== 'https://widgets.example.test') return;
  if (event.data?.type !== 'resize') return;
  frame.style.height = `${event.data.height}px`;
  console.log(`frame height: ${event.data.height}px`);
});
Text
frame height: 420px

The frame watches its root element with a ResizeObserver, so a late image or an opened menu triggers a new message. The parent checks the origin, checks the message type, then sets the height. Without the origin check, any page could resize your frame. The target origin in postMessage keeps the number from leaking elsewhere.

Setting the height to the content height stops the frame scrolling inside itself. The numbers are an example. For a same-origin frame, read frame.contentDocument.documentElement.scrollHeight after the load event. See iframe.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.