Problem:
I wanted to embed a form into an webpage. Easy enough!
As I tested the form in the iframe, I noticed the form height would
change during validation. As error messages pop up, the form height would increase,
and before I knew it, half the form was hidden in the iframe.
I needed to figure out a way to adjust the iframe according to the
content height in the iframe.
Solution:
I discovered a way for an iframe and it’s parent to communicate. In the iframe content (child), I figured out
a way to post a message (body height) to the parent. When an error occured, I would run this code:
let body =
document.getElementsByTagName('body')[0];
parent.postMessage('formHeight',
body.offsetHeight);
In the parent page, I set up an event handler to always be
listening for a message from the child.
When the parent detects a message, I can receive and use the data for
whatever I want. In my case, change
the height of the iframe:
window.addEventListener('message',
function(e){
let
iframe = document.getElementById('iframe');
iframe.style.height
= e.data + 'px';
});
Warning:
This solution is not cross domain friendly. You’ll get a lovely CORS error.
Comments
Post a Comment