1 year ago

#77037

test-img

tj001

Script Produces "Uncaught TypeError: Cannot read properties of null (reading 'scrollHeight')" When Iframe is Reloaded

I added the highlighted script to my PHP page's header to automatically adjust iframe size to iframe contents; the script is activated w/ <script>sizeit("#frame_id");</script>, and the results are as expected / it works well.

However, on iframe reload (w/ a "right-click / Reload iframe" selection within the iframe) the script produces the following error: "Uncaught TypeError: Cannot read properties of null (reading 'scrollHeight')"

It seems scrollHeight isn't available on iframe reload.

<script>
function sizeit(id){
    let iframe = document.querySelector(id);

    iframe.addEventListener('load', function() {
        setInterval(function() {
            iframe.style.height = iframe.contentDocument.body.scrollHeight + 10 + 'px';
            iframe.style.width = 100 + '%';
        });
    });
}
</script>

Any thoughts on how to resolve this? The error message does not appear when the entire page is reloaded, only when an iframe is reloaded.

javascript

iframe

0 Answers

Your Answer

Accepted video resources