我可以使用window.postMessage进行同步跨域通信吗?
我正在考虑直接使用 window.postMessage 进行跨域通信。
如果我这样做:
postMessage()
从父框架- 加载一个 iframe
window.addEventListener("message", callback, false);
从子 iframe
我什么时候会收到消息加载iframe之前发布的内容会被执行吗?他们一定会被处决吗?有时间保证吗?
我想从顶部框架传递一个影响子框架初始化的参数。
I'm thinking of using window.postMessage directly for cross-domain communication.
If I do:
postMessage()
from the parent frame- Load an iframe
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
postMessage() 函数是异步的,这意味着它将立即返回。所以你不能与它进行同步通信。
在您的示例中,发布的消息将消失在空白中,因为在执行 postMessage() 函数时没有消息事件的侦听器。
如果您先加载 iframe,然后调用 postMessage(),那么可能会出现计时问题。 (根据我的经验,没有,父代码总是先执行,但我不确定这一点。)
下面是我针对不知道 iframe 何时准备就绪的问题的解决方案。
在父窗口中:
在 iframe 中:< /em>
无论谁从对方收到第一条消息,然后开始真正的通信。
根据我的经验,从父级到 iframe 的消息总是会丢失,因此当父级收到来自 iframe 的消息时,通信就会开始。但在此设置中,哪个先启动并不重要。
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.
要从父窗口向 iframe 发送第一条消息,您只能在 iframe 加载后执行此操作,在此之前您甚至无法将消息从子窗口发送到父窗口。
因此,为了做到这一点,请为 iframe 提供一个 onload 处理程序,以便您可以使用 postmessge()。
考虑以下相同的代码。
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.