How to resize a cross domain iframe when content changes?

by filiberto , in category: HTML & CSS , a month ago

How to resize a cross domain iframe when content changes?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , a month ago

@filiberto 

To resize a cross domain iframe when the content changes, you can use the postMessage API in JavaScript to communicate between the parent page and the iframe. Here's a step-by-step guide on how to do this:

  1. Add an event listener in the parent page that listens for messages from the iframe:
1
2
3
4
5
6
7
window.addEventListener('message', function(event) {
    // Check if the message is from the iframe
    if (event.source === iframe.contentWindow) {
        // Resize the iframe based on the new content height
        iframe.style.height = event.data + 'px';
    }
});


  1. In the iframe content, after the content changes and you want to resize the iframe, send a message to the parent page with the new content height:
1
2
var newHeight = document.body.scrollHeight;
parent.postMessage(newHeight, '*');


  1. Make sure that the iframe has the sandbox attribute set to allow communication with the parent page:
1
<iframe src="https://example.com" sandbox="allow-same-origin allow-scripts"></iframe>


With these steps, the parent page will listen for messages from the iframe and resize it accordingly when new content is loaded. This allows for a seamless resizing of the iframe when the content changes in a cross domain scenario.