Communication between an iframe and its parent window
Written byPhuoc Nguyen
Created
08 Mar, 2020
Category
Level 2 — Intermediate
#Send data from an iframe to its parent window
js
// Called from the iframe
window.parent.postMessage(message, '*');
Where
`message`
is a string. If you want to send multiple data, you can encode in JSON:js
// Called from the iframe
const message = JSON.stringify({
message: 'Hello from iframe',
date: Date.now(),
});
window.parent.postMessage(message, '*');
#Send data from a page to its child iframe
js
// Called from the page
frameEle.contentWindow.postMessage(message, '*');
Where
`frameEle`
represents the iframe element.#Receive the sent data
In the iframe or main page, you can listen on the
`message`
event to receive the sent data:js
window.addEventListener('message', function (e) {
// Get the sent data
const data = e.data;
// If you encode the message in JSON before sending them,
// then decode here
// const decoded = JSON.parse(data);
});
#Tip
If you send or receive message from different iframes, you can include a parameter to indicate where the message comes from.
js
// From a child iframe
const message = JSON.stringify({
channel: 'FROM_FRAME_A',
...
});
window.parent.postMessage(message, '*');
Then in the main page, you can distinguish the messages by looking at the parameter:
js
window.addEventListener('message', function (e) {
const data = JSON.parse(e.data);
// Where does the message come from
const channel = data.channel;
});
Here is an example demonstrates how to send a simple message between a page and a child iframe:
#Demo
#See also
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn