Communication between an iframe and its parent window
Send data from an iframe to its parent window
window.parent.postMessage(message, '*');
Where message
is a string. If you want to send multiple data, you can encode in JSON:
const message = JSON.stringify({
message: 'Hello from iframe',
date: Date.now(),
});
window.parent.postMessage(message, '*');
Send data from a page to its child iframe
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) {
const data = e.data;
});
Tip
If you send or receive message from different iframes, you can include a parameter to indicate where the message comes from.
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);
const channel = data.channel;
});
Here is an example demonstrates how to send a simple message between a
page and
a child iframe:
Demo
Communication between an iframe and its parent window
See also