# Resizing an iframe to match contents inside

Tags: web

Reading time: 2 minutes

Description: Resizing an iframe from within itself to match its contents






# script.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
window.onload = function () {
    const doc = parent.document.getElementById('resizeableiframe');
    if (doc != null) {
        const newHeight = Math.max(
            document.body.offsetHeight,
            document.documentElement.offsetHeight
        );
        console.log("Setting height to " + newHeight);
        doc.style.height = newHeight + 'px';
    }
}

# index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <iframe title="resizeableiframe" id="resizeableiframe" src="test.html"
            style="width:100%; border:solid 1px black;"></iframe>
    </body>
</html>

# test.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <h1>test</h1>
        <br />
        <br />
        <a href="test2.html">test2</a>
    </body>
</html>

# test2.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <h1>test2</h1>
        <pre style="font-family: 'monospace';">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </pre>
        <a href="test.html">test</a>
    </body>
</html>