gpt4 book ai didi

javascript - 通过 receiveMessage 恢复等待异步脚本

转载 作者:行者123 更新时间:2023-11-27 23:51:08 24 4
gpt4 key购买 nike

Client1 在窗口内有一个 iframe。Client2 通过异步脚本向 Client1 发送 postMessage(),然后 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 () {

});

关于javascript - 通过 receiveMessage 恢复等待异步脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32696399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com