← Back toHTML DOM

Communication between an iframe and its parent window

Written byPhuoc Nguyen
Category
Level 2 — Intermediate
Created
08 Mar, 2020

Send data from an iframe to its parent window

// 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:
// 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

// 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:
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.
// 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:
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? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

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