如何从iframe js发送窗口事件

问题描述 投票:0回答:1

我想将带有数据的事件从 iframe 发送到主应用程序,我使用以下代码结构:

在 iframe 中调度事件

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

监听主应用程序内的事件

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

但这不起作用。

javascript event-handling
1个回答
0
投票

一切几乎都是正确的,但我必须将事件分派给包含 iframe 的父级。 iframe 的父级是我的主应用程序,它正在侦听事件。所以下一个代码片段就可以正常工作了:

将 iframe 中的事件调度到父级(主应用程序)

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

监听主应用程序内的事件

window.addEventListener("play-key", (e: any) => {
  this.setSelectedKey(e.detail);
}, false);
© www.soinside.com 2019 - 2024. All rights reserved.