You can adjust the height of an iframe to fit its content in JavaScript by accessing the iframe’s contentWindow property and setting the height ‘property of the iframe’s document object to the height of the content. Here’s an example:

<iframe id="myFrame" src="https://deepdeveloper.in"></iframe>
<script>
  function resizeIframe() {
    var iframe = document.getElementById("myFrame");
    var iframeDoc = iframe.contentWindow.document;
    iframe.height = iframeDoc.body.scrollHeight;
  }
  window.onload = resizeIframe;
</script>

The resizeIframe function is called when the page is loaded and sets the iframe’s height to the height of the content.

You can also use .contentDocument instead of .contentWindow.document if you are using modern browsers.

You can also use window.addEventListener("message", messageReceived, false); to listen for message from the iframe and update the iframe height accordingly.

<iframe id="myFrame" src="https://deepdeveloper.in"></iframe>
<script>
  window.addEventListener("message", messageReceived, false);
  function messageReceived(event) {
    if (event.data && event.data.height) {
      document.getElementById("myFrame").style.height = event.data.height + "px";
    }
  }
</script>

and on the iframe’s content you can use

<script>
  window.parent.postMessage({height: document.body.scrollHeight}, "*");
</script>

This way, the iframe’s height will always match the height of its content, even when the content changes dynamically.

Also Read:

Categorized in: