Snippet which uses postMessage to automatically set the height of an iframe to fit the height of the page inside it. Requires you to add a script to the page inside the iframe.
https://github.com/andfinally/iframe-autoheight
- Copy the two scripts
iframe-autoheight-parent.min.jsandiframe-autoheight-child.min.jsand the stylesheetiframe-autoheight.cssfrom thedistfolder to your server. - Change
permittedOrigininiframe-autoheight-parent.min.jsto the hostname of the page inside the iframe. For example, if the URL of the child page ishttps://mysite.com/content,permittedOriginshould behttps://mysite.com. You can do this by runninggulpand modifyingsrc/scripts/iframe-autoheight-child.es, or change it in the minified JS file directly. - Include
iframe-autoheight-parent.min.jsandiframe-autoheight.cssin the parent page that contains the iframe. - Include
iframe-autoheight-child.min.jsin the child page inside the iframe. - Ensure your iframe has a
nameattribute and give it the classiframe-autoheight. I also recommendscrollingandframeborderattributes like in this example:<iframe src="content.html" name="nom" class="iframe-autoheight" scrolling="no" frameborder="0"></iframe>
- The script in the page inside the iframe sends a postMessage to the parent page on
DOMContentLoadedor on load, and also whenever it's resized. - The script in the parent page adjusts the height of the iframe to fit the height of the
documentelement in the child page.
- Iframe must have a
nameattribute. - Iframe must have
classattributeiframe-autoheightto take on the simple styles defined iniframe-autoheight.css. - Iframe should have
scrollingattributeno. event.originin the parent page must match the origin of the page in the iframe.
- The script in the parent page needs to be parsed before the one in the page inside the iframe. If the parent page has a lot of slow-loading content you may find you need to place the parent script higher up in the loading order of the page, for example in the head element.
- We should add top and bottom margins to the calculation of height in
iframe-autoheight-child.es. - We could optimise the parent script by splitting it into two, one small part caching all postMessages received, and the other processing the cached messages once it's loaded.
gulpto start a watch process which transpiles the ES6 and SASS files insrcand copies the resulting files to thedevanddistfolders.gulp startto run the build, start serving the demo at http://localhost:8087, and start the watch process.