简体   繁体   中英

How to trigger iFrame load within an iFrame?

I send messages to iFrame, but only on iFrame load event. Want to trigger it manually without page reload, after changing DOM.

Explanation: It is kind of survey and on page change I send page size. Problem happens when I insert new image in DOM, than I need to tell parent page and trigger the iFrame load event. The message goes parent->iframe, than iframe->parent only on iFrame load.

Instead of triggering a load event, you should use a message posted by your IFrame.

JavaScript in outer frame (this attaches an event listener for messages and shows an alert when a message is received):

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 in inner frame (this sends a message to the parent window - it should trigger the listener there and show the alert):

// 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");

Instead of "Hello World!" , you can also pass JS objects.

It also works the other way round: If you install a message listener in your IFrame as well, then you can also send messages from the outer frame to the inner one, using something like document.getElementById('myIframe').contentWindow.postMessage(...) .

See also: http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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