Sizing of embedded iframes to their content box size is a common webdev problem. ResizeObserver can help with a solution.
Full solution needs to solve several distinct problems:
1) iframe needs to know when its size has changed.
ResizeObserver solves this by observing <body>
's size changes.
Note: this only works in standards mode, because body height is 100% in quirks.
// This code is executed inside iframe let ro = new ResizeObserver(entries => { let idealSize = computeIdealSize(isImage); window.parent.postMessage({ name: "iframeResize", width: idealSize.width, height: idealSize.height }, '*'); }); ro.observe(document.body);
2) iframe must decide what its size should be.
When document is text, the width of text will always be at least initial width of iframe. Height will be determined by text length.
When document is image, width and height are determined by image size.
3) iframe needs to communicate its size to containing window.
This can be done with postMessage
API.
// This code goes into containing window window.addEventListener("message", ev => { if (ev.data && ev.data.name == "iframeResize") { let iframe = findEventSourceIframe(ev.source); if (iframe) { iframe.style.width = ev.data.width + "px"; iframe.style.height = ev.data.height + "px"; } } }, false);
iframeResize.js is a library implementation.