Damián Pumar

← Back to blog

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:

The postMessage method receives two parameters:

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

Recent Blogposts

  • Add new functionality with less code ⌨️

    Add new functionality with less code ⌨️

    In this post I will explain how can you add it new functionality with less changes are posible, without modifying the design of your application, without breaking any SOLID principles using the decorator pattern.

  • Frontend dependency injection container

    Frontend dependency injection container

    do you know what dependency injection is? How do dependency injection containers work? In this post I will explain how it works and how you can implement it in your project, we will see the advantages, disadvantages with code examples.

  • Reuse Vue component in a directive ♻️

    Reuse Vue component in a directive ♻️

    In this post I will show you how to reuse a vue component in a directive without duplicate code or create vanilla javascript replicating this behavior. Sometimes it is necessary to do it because you will have to rewrite all the vue code in vanilla javascript, and sometimes that would be a lot of work, right?