简体   繁体   English

如何从父级调度 Iframe 中的自定义事件?

[英]How to dispatch a custom event in Iframe from a parent?

I currently have addEventListener and dispatchEvent in the same file as seen below:我目前在同一个文件中有addEventListenerdispatchEvent ,如下所示:

<!DOCTYPE html>
<html>
<body>
<script>
    addEventListener("hello", function(event) {
        console.log( event.detail.name);
    });

    dispatchEvent(new CustomEvent("hello", {
        detail: { name: "Patrick" }
    }));
</script>
</body>
</html>

This works fine, but my goal is to split these two into separate files.这很好用,但我的目标是将这两个分成单独的文件。 The addEventListener would be located in an external file and loaded via Iframe and dispatchEvent would be sent from the main file. addEventListener将位于外部文件中并通过 Iframe 加载,并且dispatchEvent将从主文件发送。

How can I dispatch events in Iframes from the parent?如何从父级分派 iframe 中的事件?

If someone else is still looking for an answer, I figured out that you can just call functions from the Iframe by using:如果其他人仍在寻找答案,我发现您可以使用以下方法从 Iframe 调用函数:

frames[0].myFunction();

So technically you can just create a new function inside the Iframe, eg myFunction, and use it to dispatch the event.所以从技术上讲,您可以在 Iframe 中创建一个新的 function,例如 myFunction,并使用它来调度事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM