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.
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.
// 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);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`);
});frame height: 420pxThe 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.