skip to Main Content

I want to send an event with data from an iframe to the main application. To do it I use this structure of code:

Dispatch event in the iframe

window.dispatchEvent(new CustomEvent("play-key", { detail: 'some-custom-key' }));

Listen for the event within the main app

window.addEventListener("play-key", (e: any) => {
  this.setSelectedKey(e.detail);
}, false);

But it doesn’t work.

2

Answers


  1. Chosen as BEST ANSWER

    Everything is almost correct but I have to dispatch event to the parent which contains an iframe. The parent of the iframe is my main app, which is listening for the events. So next code snippet just works fine:

    Dispatch event in the iframe to the parent (main app)

    window.parent.dispatchEvent(new CustomEvent("play-key", { detail: 'some-custom-key' }));
    

    Listen for the event within the main app

    window.addEventListener("play-key", (e: any) => {
      this.setSelectedKey(e.detail);
    }, false);
    

  2. Your code seems to be well-structured. Here is a simplified snippet for you to better understand the communication process between the main file and the iframe.

    Main file:

    <!DOCTYPE html>
    <html>
    <head>
        <title>IFrame Event Test</title>
    </head>
    <body>
    <div>
        <p>Main Application</p>
        <p>Selected Key: <span id="selected-key">None</span></p>
    </div>
    <iframe id="myIframe" src="./iframe.html">
    </iframe>
    <script>
        window.addEventListener("play-key", (e) => {
            console.log("Event captured in main app", e.detail);
            document.getElementById("selected-key").innerText = e.detail;
        }, false);
    </script>
    
    </body>
    </html>
    

    Iframe file:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <script>
            // Dispatch event in the iframe
            window.parent.dispatchEvent(new CustomEvent("play-key", { detail: 
            "hello" }));
        </script>
    </body>
    </html>
    

    Ensure that both HTML files are hosted on the same domain and that the paths to the iframe are correctly specified in the main file. Feel free to check the developer console for any potential errors or warnings that might provide additional insights into the issue.

    If you encounter any further problems, please share any error messages or unexpected behaviors for a more accurate diagnosis.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search