Published on January 3, 2024 by Damián Pumar
Hi 👋
In this post I will explain how can you send data from <iframe>
to its parent window without any cors restriction and sending complex objects.
Imagine that you have a website that has an <iframe>
that loads a third party website, and you need to send data from the <iframe>
to the parent window.
Let’s start with child <iframe>
code
// child.html
<div>
<button onclick="sendDataToParent()">Send data to parent</button>
</div>
<script>
function sendDataToParent() {
const message = {
event: "your_event_id",
data: {
name: "Damián",
lastName: "Pumar",
age: 32,
},
};
window.parent.postMessage(JSON.stringify(message), "*");
}
</script>
With postMessage we can send data from the <iframe>
to the parent window, but we have some restrictions:
- We can only send strings.
- But we can solve this problem using the
JSON.stringify
andJSON.parse
methods.
- But we can solve this problem using the
- We can only send data to the parent window.
- But we can solve this problem using the
window.parent
property.
- But we can solve this problem using the
The postMessage method receives two parameters:
- The first parameter is the data that we want to send to the parent window.
- The second parameter is the origin of the parent window, this parameter is optional, but it is recommended to use it to avoid security problems.
So, we have a button that when we click on it, we send a message to the parent window using the postMessage
method.
Now let’s see the parent window code
// parent.html
<iframe src="child.html"></iframe>
<script>
window.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
console.log(data);
// {
// event: "your_event_id",
// data:
// { name: "Damián",
// lastName: "Pumar",
// age: 32
// }
// }
});
</script>
Easy right? 🤓
Hope you like it, see you in the next post 👋
Bye 🙌
Written by Damián Pumar
Something wrong? Let me know 🙏
← Back to blog