It may be difficult in practice, but when it is, we need to be able to immediately figure out how to do it.

Iframe sends a message to the parent page

On the iframe page, call the postMessage method with window.parent to send a message to the parent page.

window.parent.postMessage(message, The '*');
Copy the code

Message can only be a String, so if you want to send multiple pieces of data, you can use JSON serialized objects.

// serialize objects
const message = JSON.stringify({
  message: 'Hello'.date: Date.now(),
});
window.parent.postMessage(message, The '*');
Copy the code

The parent page sends messages to the IFrame

On the parent page, call the postMessage method with iframe.contentWindow to send a message to the iframe.

iframeEl.contentWindow.postMessage(message, The '*');
Copy the code

IframeEl represents an Iframe DOM object.

Receives the message

On both iframe and parent pages, the window listens for message events to receive messages.

window.addEventListener('message'.function (e) {
  // Get the message content data
  const { data } = e;
});
Copy the code

If the message content is a serialized object, you also need to deserialize the message content.

window.addEventListener('message'.function (e) {
  // Get the message content data
  let { data } = e;
  data = JSON.parse(data);
});
Copy the code

Specifies the domain name for sending messages

Above we use the postMessage method, passing the second argument *, which means that any domain can receive messages. If you know the domain name of the message receiver, use the second parameter to pass the domain name of the message receiver.

iframeEl.contentWindow.postMessage(message, 'https://www.baidu.com');
Copy the code

The message is sent only if the iframe points to https://www.baidu.com.