Home > Net >  How to know the actual height of an iframe's content?
How to know the actual height of an iframe's content?

Time:01-20

I have this code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function resizeiframe() {
            var Lyrics = document.getElementById("Lyrics");

            Lyrics.height = Lyrics.contentWindow.document.documentElement.scrollHeight;
        }

    </script>
</head>

<body>
    <iframe id="Lyrics" src="X-Raym_Lyrics.html" scrolling="auto" title="Lyrics" width="100%"></iframe>
    </br>
    <button type="button" id="resizeiframebutton" onclick="resizeiframe()" title="Resize">Resize</button>
</body>

</html>

When i inspect the tag body (or html tag doesnt matter is an example) from X-Raym_Lyrics.html in chrome opened outof iframe i see that my script arent able to pickup a real value of height of the content to the height of iframe. Text

Is there a way to pickup the real height of the web page.

CodePudding user response:

You can use the following JavaScript code to get the actual height of the iframe content:

var iframe = document.getElementById('yourIframeID');
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
var height =iframeDoc.body.scrollHeight;

Some resources:

  1. HTML DOM contentDocument Property: https://www.w3schools.com/jsref/prop_frame_contentdocument.asp
  2. HTML DOM contentWindow Property: https://www.w3schools.com/jsref/prop_frame_contentwindow.asp
  3. HTML DOM scrollHeight Property: https://www.w3schools.com/jsref/prop_element_scrollheight.asp

Don't forget the vote :)

  • Related