Javascript 通过receiveMessage恢复等待的异步脚本
Client1在窗口中有一个iframe。 Client2通过异步脚本向Client1发送postMessage(),然后Client1执行某些操作(绕过跨域策略限制)。到目前为止,它工作得很好。 现在Client1将postMessage()返回到Client2,这样他(2)就可以结束等待(因为执行了async.script) 如何完成 代码片段: 客户端2Javascript 通过receiveMessage恢复等待的异步脚本,javascript,angularjs,iframe,asynchronous,protractor,Javascript,Angularjs,Iframe,Asynchronous,Protractor,Client1在窗口中有一个iframe。 Client2通过异步脚本向Client1发送postMessage(),然后Client1执行某些操作(绕过跨域策略限制)。到目前为止,它工作得很好。 现在Client1将postMessage()返回到Client2,这样他(2)就可以结束等待(因为执行了async.script) 如何完成 代码片段: 客户端2 var iframe; return browser.executeAsyncScript(function (done) {
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
将执行所有匹配的处理程序,如果receiveMessage
与Client1
中的事件不同,并且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 () {
});
还添加一个
窗口。addEventListener(“消息”,receiveMessage)并调用C2中的完成和移除EventListener
(使其仅使用一次)。您能详细说明一下吗?与此同时,我已经在C2中添加了eventListener,但是如何以及何时调用done?我只是看到还有一个receiveMessage
,这与C1相同,还是您还没有决定它的外观?现在它与上面所示完全一样。我只是不明白C1中的event.source.postMessage是如何在C2中启动revice函数的。。。似乎async.script仍在等待是一个问题,因此无法调用其他函数。在async脚本中,函数完成了显示消息的操作,非常感谢!