Tommay
Tommay

Reputation: 1

How to resize the height of an iframe when its content changes?

I would like to resize the height of an iframe when its content changes (when someone clicks on a link on the iframe), with no scroll. It means that the iframe should take the height it needs on the page.

I tried to use the function onLoad but it just works the first time the iframe is loaded (not when I click on an internal link inside the iframe).

The website embedded in the iframe is in React (is it a problem?). The iframe is embedded in a different domain name (I gave authorisations with Django CSP).

Do you know how to do it? Thanks a lot!

<iframe src="https://www.example.com" width="100%" height="200px" id="iframe" marginheight="0" frameborder="0" onload="autoResize('iframe');" ></iframe>

<script language="JavaScript">
function autoResize(id){

    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}

</script>

Upvotes: 0

Views: 1004

Answers (1)

Niklas
Niklas

Reputation: 1938

I had the similar problem once. There is no automatic feature for iframes to adjust their height. You need to implement a manual form of communication of a height change between the main page (window.onmessage) and the embedded page (parent.postMessage). The tutorial I used was Medium: How to Automatically Resize an iframe and I was very happy with it.

Upvotes: 1

Related Questions