DEV Community

Cover image for Updating Iframe height based on his content.
Jhonatan Morais
Jhonatan Morais

Posted on

Updating Iframe height based on his content.


I know I know we need to avoid use Iframes. But when our client need it... We use it.

Last week, one of my clients complain that his iframe was showing the scrollbar when his height content changes because of the iframed-site-responsivity

Well, that is e real problem. But how to change the iframe height if the host-site doesn't know when the iframe content was updated?

iframe without auto-height

After some research I found a possible solution using the window.postMessage, and here goes it:

Workflow information

Basically, the idea is recursively to send a postMessage from the 'guest-page' as a signal notifying the actual page height. Now on the other side, the 'host-page' needs to has a listener, catching the message and updated the iframe height.

The code from guest-side

Here I'm using the vue. The most important lines are:

  • line 13: i set the ref of object I want to get the height.
  • line 46: I use the method iframeHeightNotify to get the page-height by ref and send the postMessage.
  • line 39: I set the page to recursively send the height.
  • line 43: I finish the recursive operation ;

IMPORTANT: As recommended by Mozzila it is not a good choice send messages using broadcast ( the * at line 50), by here is just a sample, set the target origin and validate it on the host side it is on you.

The code from host-side

Here I'm using the HTML and Jquery. The most important lines are:

  • line 16: I set an id to my iframe
  • line 7: I set the Listener and update the iframe height based on the incoming message

Final result

And here is the final result

iframe with auto-height

I hope this content be useful to you.
My best wishes See you.

Top comments (0)