On the project that I’m currently working on I had to include part of a legacy project on an iframe and I need to send a few information to it.
It have been a while since I had to do this kind of thing so I decided to make this post for future reference and to help anyone with the same problem.
When the iframe is on the same domain
If the iframe that you are embedding is on the same domain then it is really easy. You just have to enable allow-same-origin and allow-scripts on your iframe. Be aware tough that by enabling those flags you are also allowing the iframe to call functions within it’s parent. Since both are on the same domain I presume they are under your control and it will probably not be a problem.
To call a function within your iframe from the parent page:
And to call a function on the parent from your iframe:
And when the iframe is on a different domain
Back in the day we had a few ‘hacks’ that enabled us to communicate with an iframe on a different domain. Since they are kind of obsolete now, I’ll not talk about then but if you are curious you can take a look at this post.
Window.postMessage() to the rescue
The window.postMessage() allows safe communication between a page and any iframe within it so we don’t have to worry about hacking our way to success anymore. And it is really easy to use:
Just a security consideration: if you are going to add a handler for messages on your page make sure to check the event.origin to see if its coming from a known origin and when you are sending sensitive data you can use the second parameter on postMessage to make sure that only trusted domains are listening to that message.
Thanks for reading and as always if I missed something feel free to leave a comment and if you are interested you can read more about postMessage on MDN.
