A photo gallery fits neatly inside a 600-pixel iframe. Then someone opens the comments panel. The submit button disappears below the frame, a second scrollbar appears, and the host page has no idea anything changed.
Increasing the default height only moves the problem. A narrow screen produces more grid rows. A different language wraps captions onto extra lines. Client photo selection changes the visible content.
This is a practical integration problem for photo and video client galleries, where reviewing and downloading happen inside the same interface. The implementation below is a standalone design for a service you control, not a description of any particular product’s internals.
Let the child measure and the parent decide
The host cannot inspect a cross-origin iframe’s DOM. Instead, the embedded page measures its content and sends a small message. The parent validates that message before updating the iframe.
The browser provides this communication channel through window.postMessage(). Use an exact destination origin, check the sender’s origin and window reference, and validate the payload.
Keep the protocol narrow:
{
type: "gallery:resize",
version: 1,
height: 1248
}
The child requests a height. The parent still owns the surrounding layout and decides how much space to allocate.
That distinction matters when a gallery contains hundreds of images.
Measure a content wrapper, not the viewport
A tempting implementation sends document.documentElement.scrollHeight. However, document measurements can include the existing viewport height. After expanding the iframe, switching to a shorter gallery may leave it unable to shrink.
Use a dedicated wrapper whose height follows its content:
<style>
body { margin: 0; }
#embed-root { display: flow-root; }
img, video { max-width: 100%; }
</style>
<main id="embed-root">
<!-- Gallery, captions, comments, and controls -->
</main>
flow-root helps contain floats and prevents child margins from collapsing through the wrapper. Keep the content that should affect height in normal document flow.
Avoid min-height: 100vh on this wrapper. Its height would then depend on the iframe height that the parent is trying to calculate. Viewport-height-based padding can create the same circular dependency.
Absolutely positioned overlays need a separate policy: they do not automatically contribute to the wrapper’s height.
Start reporting after initialization
Inside the embedded page, use ResizeObserver to detect changes to the wrapper’s dimensions. It reacts to layout changes, including those caused by wrapping text or expanding controls.
This script runs after the wrapper exists:
const parentOrigin = "https://portfolio.example";
const root = document.getElementById("embed-root");
let active = false;
let pending = 0;
let previousHeight = -1;
function scheduleMeasurement() {
if (!active || pending) return;
pending = requestAnimationFrame(() => {
pending = 0;
const height = Math.ceil(
root.getBoundingClientRect().height
);
if (height === previousHeight) return;
previousHeight = height;
window.parent.postMessage(
{ type: "gallery:resize", version: 1, height },
parentOrigin
);
});
}
const observer = new ResizeObserver(scheduleMeasurement);
window.addEventListener("message", (event) => {
if (event.origin !== parentOrigin) return;
if (event.source !== window.parent) return;
if (event.data?.type !== "gallery:init") return;
if (event.data?.version !== 1) return;
if (!active) {
active = true;
observer.observe(root);
}
previousHeight = -1;
scheduleMeasurement();
});
For a multi-tenant service, resolve parentOrigin from validated embed configuration. Do not accept an arbitrary parent origin from a query parameter without checking it against the tenant’s approved domains.
The animation-frame callback combines pending notifications into one measurement. Comparing heights avoids repeated messages when nothing changed.
Neither mechanism fixes a circular layout dependency. The wrapper must still have a height independent of the iframe viewport.
Install the receiver before loading the iframe
On the host page, create the iframe only after preparing the message handler. Send initialization after each iframe load:
const galleryOrigin = "https://media.example";
const frame = document.createElement("iframe");
frame.title = "Client photo gallery";
frame.style.cssText =
"display:block;width:100%;height:600px;border:0";
function receiveHeight(event) {
if (event.origin !== galleryOrigin) return;
if (event.source !== frame.contentWindow) return;
const data = event.data;
if (!data || typeof data !== "object") return;
if (data.type !== "gallery:resize") return;
if (data.version !== 1) return;
if (!Number.isFinite(data.height)) return;
if (data.height < 0 || data.height > 1_000_000) return;
const height = Math.min(
5000,
Math.max(240, Math.ceil(data.height))
);
const value = `${height}px`;
if (frame.style.height !== value) {
frame.style.height = value;
}
}
window.addEventListener("message", receiveHeight);
frame.addEventListener("load", () => {
frame.contentWindow.postMessage(
{ type: "gallery:init", version: 1 },
galleryOrigin
);
});
frame.src = `${galleryOrigin}/embed/demo`;
document.getElementById("gallery-slot").append(frame);
The host page needs a gallery-slot container. Replace the example origins and route with your deployment’s values.
The source check isolates this iframe from other frames using the same service. The initial height provides space before the first response arrives.
The 5,000-pixel limit is an application choice. Above it, preserve normal scrolling inside the child document. Hiding overflow would make content inaccessible.
Handle the cases that break the demo
Reserve image space with intrinsic dimensions or an aspect ratio. Otherwise, successive image loads can repeatedly move the host page’s footer.
Keep auto-expansion bounded when using lazy loading. An expanding iframe can bring more content into its viewport, triggering more loading and further growth. Pagination or a deliberate scrolling region makes that behavior easier to control.
This example assumes ordinary HTTPS origins. A sandbox configuration that gives the child an opaque origin changes the messaging model; weakening validation to accept "null" is not an equivalent solution.
In a component-based application, remove the host listener when the embed unmounts. Disconnect the child observer and cancel pending animation frames when tearing down its integration.
Test shrinking as carefully as growing
Open a long gallery, then filter it down to three images. Expand and collapse comments. Resize the host across a grid breakpoint. Reload the iframe. Place two galleries on the same page.
Also send malformed messages and confirm they do nothing.
The useful invariant is simple: content changes may adjust the frame, but adjusting the frame must not create endless content growth. Once that holds, responsive embedding becomes a small, predictable protocol.
Top comments (0)