Quantcast
Channel: Resizing an iframe based on content - Stack Overflow
Viewing all articles
Browse latest Browse all 28

Answer by latitov for Resizing an iframe based on content

$
0
0

David Bradshaw and Chris Jacob already suggested using the postMessage approach. And I totally agree, that the proper way of doing things like these.

I just want to post an example, real code that works, in case it'll be a ready answers for some.

On the iframed-side:

<body onload="docResizePipe()"><script>var v = 0;const docResizeObserver = new ResizeObserver(() => {    docResizePipe();});docResizeObserver.observe(document.querySelector("body"));function docResizePipe() {    v += 1;    if (v > 5) {        return;    }    var w = document.body.scrollWidth;    var h = document.body.scrollHeight;    window.parent.postMessage([w,h], "*");}setInterval(function() {    v -= 1;    if (v < 0) {        v = 0;    }}, 300);</script>

Note the recursion-blocking mechanics - it was necessary because of apparently a bug in Firefox, but anyways let it be there.

On the parent document side:

<iframe id="rpa-frame" src="3.html" style="border: none;"></iframe><script>var rpaFrame = document.getElementById("rpa-frame");window.addEventListener("message", (event) => {    var width = event.data[0];    var height = event.data[1];    rpaFrame.width = parseInt(width)+60;    rpaFrame.height = parseInt(height)+60;    console.log(event);}, false);</script>

Hope it'll be useful.


Viewing all articles
Browse latest Browse all 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>