I'm thinking of using window.postMessage directly for cross-domain communication.
If I do:
postMessage()
from the parent framewindow.addEventListener("message", callback, false);
from the child iframeWhen will the messages I posted before loading the iframe be executed? Are they guaranteed to be executed at all? Are there timing guarantees?
I would like to pass a parameter from the top frame that influences the initialization of the child frame.
The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it.
In your example, the posted message will vanish in the void, because there is no listener for the message event at the time the postMessage() function is executed.
If you would load the iframe first and call postMessage() afterwards, then there could be a timing issue, maybe. (From my experience there is none, the parent code is always executed first, but I am not sure about this point.)
Below is my solution for the problem of not knowing exactly when the iframe will be ready.
In the parent window:
In the iframe:
Whoever receives the first message from the other side then starts the real communication.
In my experience, the message from the parent to the iframe always gets lost, so the communication starts when the parent receives the message from the iframe. But in this setup it is not important which one starts first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With