How to adjust the height of an iframe JavaScript
Step 1: Create the Parent Window (Parent.html)
In the parent HTML file (Parent.html
), you'll set up the parent window and the JavaScript code to handle resizing the iframe when the content changes.
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<iframe src="Child.html" id="iframe" width="100%" height="400"></iframe>
<script>
// Function to handle messages from the iframe
function handleIframeMessage(event) {
if (event.origin !== "https://your-iframe-domain.com") {
// Ensure messages are only accepted from the expected domain
return;
}
if (event.data === "resizeIframe") {
// Adjust the iframe height based on its content
const iframe = document.getElementById("iframe");
iframe.style.height = event.source.document.body.scrollHeight + 'px';
}
}
// Add an event listener to listen for messages from the iframe
window.addEventListener("message", handleIframeMessage, false);
</script>
</body>
</html>
Step 2: Create the Iframe Content (Child.html)
In the iframe content HTML file (Child.html
), you'll use the Mutation Observer to detect content changes and send a message to the parent window when necessary.
<!DOCTYPE html>
<html>
<head>
<title>Iframe Content</title>
</head>
<body>
<!-- Your iframe content here -->
<script>
// Function to send a message to the parent to request resizing
function resizeParentIframe() {
const message = "resizeIframe";
window.parent.postMessage(message, "https://your-parent-domain.com");
}
// Set up a Mutation Observer to detect changes in the iframe content
const observer = new MutationObserver(function (mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === "childList") {
// Content has changed; trigger a resize
resizeParentIframe();
break; // Exit the loop after the first mutation
}
}
});
// Specify the target node for the observer (the body of the iframe)
const targetNode = document.body;
// Configuration options for the observer (you can customize these)
const config = { childList: true, subtree: true };
// Start observing the target node for changes
observer.observe(targetNode, config);
</script>
</body>
</html>
In this updated example:
- We’ve added a Mutation Observer that listens for changes in the iframe’s content (e.g. when new elements are added or removed).
- When the observer detects a change (
childList
mutation), it calls theresizeParentIframe
function to send a message to the parent window requesting a resize. - The parent window still listens for messages and adjusts the iframe’s height as needed.
Remember to replace "https://your-iframe-domain.com"
and "https://your-parent-domain.com"
with the actual domains of your iframe and parent window. Customize the code further to match your specific use case and adjust the Mutation Observer configuration options as needed.