我可以与window.postMessage进行跨域同步通信吗? [英] Can I do synchronous cross-domain communicating with window.postMessage?

查看:253
本文介绍了我可以与window.postMessage进行跨域同步通信吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑将 window.postMessage 直接用于跨域交流.

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

如果我这样做:

  1. postMessage()来自父框架
  2. 加载iframe
  3. 子iframe中的
  4. window.addEventListener("message", callback, false);
  1. postMessage() from the parent frame
  2. Load an iframe
  3. window.addEventListener("message", callback, false); from the child iframe

我在加载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.

推荐答案

postMessage()函数是异步的,这意味着它将立即返回.因此您不能使用它进行同步通信.

The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it.

在您的示例中,发布的消息将在空白中消失,因为在执行postMessage()函数时没有消息事件的侦听器.

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.

如果您要先加载iframe,然后再调用postMessage(),则可能存在计时问题. (根据我的经验,父代码始终优先执行,但是我不确定这一点.)

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

以下是我的解决方案,用于不完全知道iframe何时准备就绪的问题.

Below is my solution for the problem of not knowing exactly when the iframe will be ready.

在父窗口中:

  1. 加载iframe(这也是异步的)
  2. 设置消息监听器
  3. 将消息发布到iframe(只需在此处尝试)
  4. 请等待更多消息

在iframe中:

  1. 设置消息监听器
  2. 将消息发布到父窗口(只需在此处尝试)
  3. 请等待更多消息

谁从对方收到第一个消息,然后开始真正的通信.

Whoever receives the first message from the other side then starts the real communication.

以我的经验,从父级到iframe的消息总是丢失,因此,当父级从iframe接收消息时,通信就开始了.但是在此设置中,哪个首先开始并不重要.

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.

这篇关于我可以与window.postMessage进行跨域同步通信吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆