Mary-Lou
Mary-Lou

Reputation: 1

Make iframe height dynamic when framed page's height changes but framed page's URL does not

I would like to iframe a content page in Word Press in a Duda website. I tried many scripts most of which did not work. This one works (almost) perfectly. Thanks, @Jeremy!

When navigating between different pages that have different URLs within the iframe, the iframe height adjusts seamlessly. Amazing!! There is only one minor drawback: when the current iframed page's height changes (e.g. by sliding open additional filters in a search menu with the URL remaining the same), the iframe size will not adjust. Is this something that could be easily fixed?

Page with iFrame / Parent Window:

window.addEventListener("message", (event) => {
    if (event.data.type === "resize") {
        const iframe = document.querySelector("iframe");
        iframe.height = event.data.value + "px";
    }
}, false);

Page with iframed content / Child iFrame Window:

window.addEventListener("load", (event) => {
    const el = document.querySelector("html");

    const styles = window.getComputedStyle(el);
    const margin = parseFloat(styles['marginTop']) + parseFloat(styles['marginBottom']);

    const height = Math.ceil(el.offsetHeight + margin);

    window.parent.postMessage({
        type: "resize",
        value: height
    }, "*");
});

Thanks for your help!

Upvotes: 0

Views: 86

Answers (1)

David Bradshaw
David Bradshaw

Reputation: 13077

I wrote a library called iframe-resizer that does this. If you want to do it yourself then you need to detect a number of different events that can cause the content of the iframe to resize. This includes

  • Window Resize
  • Iframe Resize
  • TextArea Resize
  • CSS Animation and Transition
  • Orientation Change
  • Mouse events
  • Touch Events
  • Printing
  • Ready State Change
  • Images late loading
  • Content Mutation

You need to detect each event type and then trigger a size calculation change.

The next issue is that there are a range of different ways to calculate the content hight in an iframe and they can be easy to break with reflowed CSS. So you might find the iframe is happy to size up, but not down.

Examples on how do do all these things is a bit beyond the scope of a single question, however, you can find examples of how to deal with them in library linked above.

Upvotes: 0

Related Questions