如何在iFrame中触发iFrame加载

How to trigger iFrame load within an iFrame?

本文关键字:iFrame 加载      更新时间:2023-09-26

我向iFrame发送消息,但仅在iFrame加载事件时发送。在更改DOM后,希望在不重新加载页面的情况下手动触发它。

说明:这是一种调查,在页面更改时我发送页面大小。当我在DOM中插入新图像时,会出现问题,我需要告诉父页面并触发iFrame load事件。仅在iframe加载时,消息会转到parent->iframe,而不是iframe->parent。

与其触发加载事件,不如使用IFrame发布的消息。

外部框架中的JavaScript(这会为消息附加一个事件侦听器,并在收到消息时显示警报):

window.addEventListener('message', function(e) {
    // This check can be removed for testing purposes, but for security
    // it's strongly recommended that you leave it in there and replace
    // the domain with the one of your IFrame's src, to ensure you process
    // only messages coming from your own code and not somebody else's.
    if(e.origin != "http://yourdomain.com") return;
    alert("Got a message: " + e.data);
});

内部框架中的JavaScript(这会向父窗口发送一条消息——它应该会触发那里的侦听器并显示警报):

// The second parameter can be replaced by "*" for testing, but again it
// is strongly recommended to use the domain you expect the outer frame
// to have, to ensure your message lands in the right window (in case
// another page loaded yours in an IFrame).
window.parent.postMessage("Hello World!", "http://yourdomain.com");

您也可以传递JS对象,而不是"Hello World!"

它也以另一种方式工作:如果您在IFrame中也安装了一个消息侦听器,那么您也可以使用document.getElementById('myIframe').contentWindow.postMessage(...)之类的东西将消息从外部框架发送到内部框架。

另请参阅:http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage