Client1在窗口内有一个iframe。
Client2通过异步脚本将postMessage()发送到Client1,然后Client1做一些事情(绕过跨域策略限制)。到目前为止,它运行良好。
现在Client1将postMessage()返回给Client2,以便他(2)可以结束他的等待(由于执行async.script)。

如何完成。

代码段:

客户2

var iframe;
    return browser.executeAsyncScript(function (done) {
        window.addEventListener("message", receiveMessage);
        iframe = document.getElementById("myIframe");
        iframe.contentWindow.postMessage("message", "*");
        ##### HERE COMES HOW TO END WAITING #####
    }).then(function () {

    });


客户1

script.function setup() {
            window.addEventListener("message", receiveMessage);
        }

script.function receiveMessage(event) {
            if (event.data !== "message")
                return;
            // done something
            event.source.postMessage("message", event.origin); ?????
            // sth. like this
        }


非常感谢您的提示

最佳答案

不确定Client2中的receiveMessage是什么,但是由于addEventListener将执行所有匹配的处理程序,因此如果receiveMessageClient1中的事件不同,并且done可以访问,则只需添加另一个事件。 receiveMessage`,那么您不需要我刚刚创建的新事件处理程序。

var iframe;

// The done passed in is the function to decide when to end the waiting.
// When you call `done`, the promise return by `browser.executeAsyncScript` knows its resolved
// and it'll start to execute whats in the `.then`.
return browser.executeAsyncScript(function (done) {
  // Dunno what `receiveMessage` is, or whether `done` is accessible to it,
  //so I just created another function.
  // If its separate from one in `Client1`, than put the codes in `endWaitHandler` here.
  window.addEventListener("message", receiveMessage);

  var endWaitHandler = function() {
    // When we receive the message, call done to resolve promise
    done();

    // Remove the endWaitHandler so it won't get register many times if
    // this function called multiple times.
    window.removeEventListener("message", endWaitHandler);
  };

  // Register before sending the message.
  window.addEventListener("message", endWaitHandler);

  iframe = document.getElementById("myIframe");
  iframe.contentWindow.postMessage("message", "*");
}).then(function () {

});

07-24 15:06