I need a solution for auto-adjusting the width
and height
of an iframe
to barely fit its content. The point is that t
I had to do this myself in a context of a web-extension. This web-extension injects some piece of UI into each page, and this UI lives inside an iframe
. The content inside the iframe
is dynamic, so I had to readjust the width and height of the iframe
itself.
I use React but the concept applies to every library.
Inside the iframe
I changed body
styles to have really big dimensions. This will allow the elements inside to lay out using all the necessary space. Making width
and height
100% didn't work for me (I guess because the iframe has a default width = 300px
and height = 150px
)
/* something like this */
body {
width: 99999px;
height: 99999px;
}
Then I injected all the iframe UI inside a div and gave it some styles
#ui-root {
display: 'inline-block';
}
After rendering my app inside this #ui-root
(in React I do this inside componentDidMount
) I compute the dimensions of this div like and sync them to the parent page using window.postMessage
:
let elRect = el.getBoundingClientRect()
window.parent.postMessage({
type: 'resize-iframe',
payload: {
width: elRect.width,
height: elRect.height
}
}, '*')
In the parent frame I do something like this:
window.addEventListener('message', (ev) => {
if(ev.data.type && ev.data.type === 'resize-iframe') {
iframe.style.width = ev.data.payload.width + 'px'
iframe.style.height = ev.data.payload.height + 'px'
}
}, false)