Html5 - Cross Browser Iframe Postmessage - Child to Parent

HTML5 - Cross Browser iframe postMessage - child to parent?

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
var key = e.message ? "message" : "data";
var data = e[key];
//run function//
},false);

Got it to work with the above in the parent page and the following in the child page -
   

parent.postMessage("loadMyOrders","*");  //  `*` on any domain         

Code copied from here.

Communicating cross-origin from parent to child iframe

You should be able to use .postMessage() between any two cooperating windows. It doesn't matter which direction you are sending the message. If it is not working in one direction, then there is probably an error in the implementation. You may need to make sure you have the proper window object.

For an iframe, you would want to use the .contentWindow property to get its window in modern browsers.

Some good documentation here: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

Sending message from child to parent iframe

Your parent load handler gets called after the iframe load handler. This leaves the postMessage sent from the child frame not handled.

From the MDN docs:

The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images, scripts, links and sub-frames have finished loading.

You need to do the postMessages at a time that you are sure the listeners are already registered. While you know that the child listener will be available before the parent load event, it still would be good practice to implement in a generic way and not depend on this order, so that you could use the same framework code, regardless if you are in parent or a child frame.

Another recommendation would be to not do things on the window load event, as it may fail to trigger in some situations. A better choice is DOMContentLoaded.



Related Topics



Leave a reply



Submit