Can I do synchronous cross-domain communicating with window.postMessage?

偶尔善良 提交于 2019-12-12 08:54:16

问题


I'm thinking of using window.postMessage directly for cross-domain communication.

If I do:

  1. postMessage() from the parent frame
  2. Load an iframe
  3. window.addEventListener("message", callback, false); from the child iframe

When 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.


回答1:


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 an timing issue, maybe. (From my experience there is none, the parent code is always execute 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:

  1. Load the iframe (this is asynchronous, too)
  2. Set up message listener
  3. Post message to the iframe (just trying here)
  4. Wait for more messages to come

In the iframe:

  1. Set up message listener
  2. Post message to the parent window (just trying here)
  3. Wait for more messages to come

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.




回答2:


To send the first message to the iframe from the parent window, you can only do it once the iframe is loaded and before that you can not even send the message from child to parent. So in order to do so provide a onload handler for the iframe so that you can use the postmessge(). Consider the following code for the same.

ifrm.setAttribute('src','www.yoururl.com'));
document.body.appendChild(ifrm);
ifrm.onload = function() {
   this.contentWindow.postMessage(dataObject,'targetWindow');
}


来源:https://stackoverflow.com/questions/9062682/can-i-do-synchronous-cross-domain-communicating-with-window-postmessage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!