簡體   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