繁体   English   中英

如何触发iFrame中的iFrame加载?

[英]How to trigger iFrame load within an iFrame?

我将消息发送到iFrame,但仅在iFrame加载事件中发送。 想要在更改DOM后手动触发它而不重新加载页面。

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

而不是触发加载事件,您应该使用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");

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

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

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

暂无
暂无

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

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