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
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)
Listen for the event within the main app
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:
Iframe file:
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.